Topic 6716

I need some help with this read/write code used for a script debugger 3 libary. Could anyone help me with it.

-- writes/reads from/to list of strings
-- don't think it works yet

property filepath : ""
property fileID : 0

on writeListToFile(theStringList, filepath, overWrite)
	try
		set fileID to open for access alias filepath with write permission
	on error number errorNum
		error number 0 -- reset error
		return errorNum
	end try
	
	if overWrite then
		set eof of fileID to 0
	end if
	
	repeat with theString in theStringList
		try
			write theString & return as text to fileID
		end try
	end repeat
	
end writeListToFile

on readFileToList(filepath)
	local theString, theStringList
	
	copy {} to theStringList
	
	try
		set fileID to open for access filepath
	on error number errorNum
		error number 0 -- reset error
		return errorNum
	end try
	
	repeat
		try
			set theString to read fileID as text until return
			set end of theStringList to {theString}
		on error
			exit repeat
		end try
	end repeat
	
	try
		close access fileID -- added this in the forum editor, not script editor. :)
	end try
	
	return theStringList
end readFileToList

It’s been a while since I’ve worked with AppleScript but it’s coming back to me. Any help would be much appreciated. I hope the script code is self explanitory.

First of all, is there a problem with the script? You posted the script but didn’t say what (if anything) was wrong with it.

That said, there are easier ways of saving a list to a text file.

For a start, instead of looping through the list, writing out each string in turn, you can write the entire list in one go:

set theFile to open for access file filepath with write permission
set {oldDelims, my text item delimiters} to {my text item delimiters, return}
write (theList as string) to theFile
set my text item delimiters to oldDelims -- restore the TIDs
close access theFile

Likewise, when reading the file back in, you can do it in one statement:

set theStringList to read file filepath using delimiter {return}

As I’ve mentioned before (see this link: http://macscripter.net/exchange/index.php?id=P219), you can read/write to files in native AppleScript classes without the need to coerce to strings and back.

Jon