Hi,
I’m new to Applescript and want to open a file to read it’s contents into a variable.
I used …
tell application “Finder”
set tempFile to ((path to desktop folder)) as text) & “myFile.txt”)
open for access tempFile
set myMessage to read tempFile
close access tempFile
display dialog the myMessage buttons {“OK”} default button 1
end tell
I just get a message “Can’t make myFile.txt into a file”
If the file doesn’t already exist it creates an empty file on the desktop but if it does exist nothing happens. I want it to read an existing file contents.
Help greatly appreciated, Thanks.
“read” is part of the Standard Additions osax, so you don’t need the Finder, and I encourage you to don’t use it, since it could carry unexpected results some times. Just:
set tempFile to (path to desktop as text) & "myFile.txt"
set myVar to read file tempFile
The specifics of why your script doesn’t work lies in the two statements:
set tempFile to ((path to desktop folder)) as text) & “myFile.txt”)
and:
open for access tempFile
In the first line, tempFile is a string/text object, nothing more.
In the second line you’re asking AppleScript to ‘open for access’ a string. Can’t happen. Won’t happen. Strings cannot be opened in this manner.
The simple solution is to coerce the string (that represents a pathname) into a file. This is easily done by prepending the keyword ‘file’:
set tempFile to ((path to desktop folder)) as text) & “myFile.txt”)
open for access file tempFile
…
Or, as jj pointed out, you can just read the file directly without explicitly opening it.