I seem to be having problems reading a file line-by-line. This is supposed to be really easy, even for beginners. All the languages seem to have this sort of construct for reading through text files.
In the book it says:
read file (whatever) (before | until) return
depending on whether or not to throw away the delimiter.
I tried both “before” or “until” on a simple two-line text file, and got the whole file back.
Trying with eof or tab gets the expected result, just not ‘return’.
I tried using pico instead of TextEdit to save the file, in case TextEdit was doing something bizarrely complicated with a simple text file, but this gave the same result.
I then tried typing in \n for newline (another example from the book), and found that Applescript evaluated it into a new line when it syntax-checked the file, which wasn’t that helpful.
Eventually I read the file into a variable and used the keyword ‘paragraph’ to get the lines, which seems to work, but why didn’t ‘read file f before return’ work?
Model: MacMini (PPC)
AppleScript: whatever comes with Tiger
Browser: Safari 417.8
Operating System: Mac OS X (10.4)
In that context, return is a carriage return (aka ASCII character 13). It’s quite likely that your file is using line feeds (aka ASCII character 10). If that’s the case, then this would have worked:
read file f before (ASCII character 10)
However, using ˜paragraphs’ should get the desired result, regardless of which line endings are being used.
A lot of OSX apps use linefeeds instead of carriage return. You can do something like this:
set f to choose file
set lf to ASCII character 10
read f until lf
Note that this is a one shot read. If you want to use the file marker, you need to use the reference number returned from ‘open for access’.
set f to choose file
set lf to ASCII character 10
set p to {}
set ref_num to (open for access f)
try
repeat
set t to read f until lf
set end of p to t
end repeat
close access ref_num
on error
close access ref_num
end try
return p
As you found out, getting paragraphs works no matter what the paragraph endings are.
On way to find out the line endings is to read the text and test for linefeed or return:
set f to choose file
set lf to ASCII character 10
set t to read f
if t contains lf then
set e to lf
else
set e to return
end if
read f until e
There’s also the combo linefeed and return used as line endings on some files, but rarely in Apple.