problem with read file

I am trying to create a script that will batch thru a ton of text files and remove content. The remove content part works fine. My problem is that I am getting an error trying to repeat thru files when I get to the open for access


tell application "Finder"
	set thefolder to choose folder
	set thefiles to items of thefolder
end tell

repeat with aitem in thefiles
	open for access aitem
	try
		set x to (read aitem)
	on error
		close access aitem
	end try

	set PartToRemove to text ((offset of "<AuditPool>" in x)) thru -7 of x
	set AppleScript's text item delimiters to PartToRemove
	set theParts to text items of x
	set AppleScript's text item delimiters to ""
	set w to theParts as string
	set fRef to (open for access file thePath with write permission)
	close access fRef
	
	my WriteToFile(w, thePath, false)
end repeat
on WriteToFile(this_data, target_file, append_data)
	try
		set the target_file to the target_file as string
		set the open_target_file to open for access file target_file with write permission
		if append_data is false then set eof of the open_target_file to 0
		write this_data to the open_target_file starting at eof
		close access the open_target_file
		return true
	on error
		try
			close access file target_file
		end try
		return false
	end try
end WriteToFile

Hi,

you’re trying to write to the file after the close statement which will fail.
Actually you can open a file once, do all your read and write operations and close it at the end.
This is a version with a more robust error handling, for example it leaves a text file unchanged if the search term is not found



set thefolder to choose folder
tell application "Finder" to set thefiles to files of thefolder

repeat with aitem in thefiles
	set currentFile to aitem as text
	try
		set fileDescriptor to open for access file currentFile with write permission
		set theText to read fileDescriptor
		set auditOffset to offset of "<AuditPool>" in theText
		if auditOffset > 0 then
			set PartToRemove to text auditOffset thru -7 of theText
			set TID to text item delimiters
			set text item delimiters to PartToRemove
			set theParts to text items of theText
			set text item delimiters to ""
			set editedText to theParts as text
			set text item delimiters to TID
			
			set eof of the fileDescriptor to 0
			write editedText to fileDescriptor starting at eof
		end if
		close access fileDescriptor
	on error
		try
			close access file currentFile
		end try
	end try
end repeat