By Alvin Alexander. Last updated: May 1, 2017
I just ran into a situation where I wanted to use AppleScript to read some file contents into a list/array, and came up with the following code:
set theFile to "/Users/al/Projects/Scala/Sarah/scripts/thank_you.data" set fileHandle to open for access theFile set thankYous to paragraphs of (read fileHandle) close access fileHandle
I can confirm that this code works on my Mac OS X 10.6.8 system. The variable thankYous
is a list/array that contains the lines from my file.
After reading the file contents into a list, I then use the following code to have my computer randomly "speak" one of the lines that I retrieved from the file:
set numThanks to count of thankYous set rn to (random number from 1 to numThanks) set reply to item rn of thank_yous say reply
An AppleScript file reading function
In the real world, what I actually did was to create this AppleScript file-reading code as a function:
-- -- An AppleScript function that reads a file and returns the lines -- from that file as a list. -- on returnFileContentsAsList(theFile) set fileHandle to open for access theFile set theLines to paragraphs of (read fileHandle) close access fileHandle return theLines end
I then call this function like this:
set thank_yous to CommonLib's returnFileContentsAsList("/Users/al/Projects/Scala/Sarah/scripts/thank_you.data") set numThanks to count of thank_yous set rn to (random number from 1 to numThanks) set reply to item rn of thank_yous say reply
In summary, if you need some AppleScript code that demonstrates how to read file contents into an array/list, I hope these examples has been helpful.