Hi everyone. I’m trying to create a script that will read a text file which contains URLs delimited by carriage-returns (or commas or whatever), and then load the URLs in Internet Explorer. I can figure out how to read the entire file using “read”, but how do I read only one line at a time?
Ok, I’m going to tout the many virtues of Text Item Delimiters here once again. Sue me.
Using TIDs, you can separate your read file into a list of items, giving it whatever you like as your delimiter. In your case, it seems ‘return’ is appropriate since you already know the typed URLs are return-delimited.
set theText to (read file "JasperX:test.txt")
set AppleScript's text item delimiters to return
set theList to every text item in theText
set AppleScript's text item delimiters to ""
Note in this example I’m using a test text file placed at the root of my hd called “test.txt” and my hard drive is called “JasperX”. (Caveat: I also did this under X with an RTF file, but it’s not pretty because RTF includes formatting info we don’t want. The above example should work in either X or 9.)
If T.J. hasn’t sold you on the virtues of TIDs yet, you might also want to look at some of the parameters that the read command can take.
read anything -- the reference number, alias, or file reference of the file to read
[using delimiters list of string] -- …or up to 2 values that separate items to read
I haven’t read files this way in quite some time but it might go something like this:
set foo to choose file with prompt "Choose a plain text file."
set bar to (read foo using delimiter return)
-- bar is now a list, with each item containing a string
-- that was separated by a return character in the
-- original file.
set moreFoo to item 1 of bar -- line 1
Rob Wrote: If I use ‘set r to return’ it works ok for me on OS X. Regarding opening the file before reading, I am under the impression that it isn’t necessary to do it. Do you have info to the contrary?
It’s necessary in this case.
It’s necessary if you want to control the file marker (the file marker is where within the file you read from).
For example in this example you read a file by say 100 bytes, then the next time you read the from file, the read starts where you last read it from, i.e.100 bytes, and so on. This continues until you close acces from the file. If you didn’t open for access the file, you’ll be reading fom the first byte every time.