As Shane hints, there’s no point in avoiding the commands which were designed for the job and which do it fastest ” albeit with a little more code.
For geek interest though, the classic way of using these commands .
-- set theFile to some HFS path.
set fileReference to (open for access file theFile with write permission)
write theData to fileReference
close access fileReference
. is done because:
- ‘open for access’ creates the file if it doesn’t exist, obtains a write-permission access to it, and returns the file-system’s reference number for the access to the script. The ‘current application’ to which ‘open for access’ was addressed then “owns” the access and no other application can use it. (So if ‘open for access’ is in a ‘tell’ statement to an application, the reference can only be used in ‘tell’ statements to that particular application.) There can be several accesses open to the file simultaneously, each with its own reference number and file-position pointer and perhaps belonging to a different application, but only one of these accesses can have write permission.
- The reference number for the opened access is passed directly to the ‘write’ command, which is thus spared the bother of checking for itself to see if the file’s open and the embarrassment of using the wrong access if there are more than one.
- The reference number is also passed directly to the ‘close access’ command, with the same advantages as for the ‘write’ command.
This three-command sequence, in conjuntion with a ‘try’ statement, is generally the fastest and safest way to create a file and write something to it.
However, if the file already exists and isn’t currently open for access, with or without write permission, the ‘write’ command is perfectly capable of opening up its own write-permission access, using it, and closing it again afterwards:
set myFilePath to (path to desktop as text) & "My file.txt"
-- For this demo, create/open the file and close the access set up in the process.
-- No need to have write permission just for this.
close access (open for access file myFilePath)
-- Now write to the file, letting 'write' sort out its own write-permission access.
write "Hello" to file myFilePath
If the two underlined conditions above are true (seldom 100% guaranteed), then ‘write’ by itself, with a ‘file’ or ‘alias’ parameter, is minutely faster than in conjunction with explicit ‘open for access’ and ‘close access’ commands. It’s not worth the risk to do this, but it’s possible.
Similarly, if the Finder is used to create a file ” a much slower way than using ‘open for access’ ” ‘write’ can open and close the file itself immediately afterwards:
tell application "Finder" to make new file at destination with properties {name:textName}
write myText to file ((destination as text) & textName)