Posted on April 13, 2008 at 6:54 pm

Readin’ and Writin’

In our last lesson, we learned about file objects. While it’s helpful to know the properties of a file, you often want to read the information from inside the file or write data to the file. AppleScript provides support for reading and writing to a file in the Standard Additions osax:

File Read Write Dictionary

Let’s create a new file using AppleScript, then write some data to it. We’ll then read the data from our new file. Here’s the code for creating a new file to which we can write data:

set f to open for access file ((path to desktop as text) & "test.txt") with write permission
write "This is a test" to f
close access f

Let’s take a closer look at it. Midway into Line 1, we tell AppleScript to create a new file on the desktop named “test.txt”. The shortcut path to desktop returns an alias to the desktop. Here, we coerce the alias to text so that we can append the name of our file, here, “test.txt”. Remember, too, that if we want to create a new file, we must use the word file explicitly because alias objects must already exist in the file system for us to use them. Note that if you have an existing alias object, you can still write to and read from that alias object.

Once we have our new file, we have to open the file for access with permission to write to it. These commands do not launch any applications to open the file. Instead, AppleScript opens the file internally as a stream of data. You must also explicitly tell you that you want to write to the file or else AppleScript will raise an error. When AppleScript opens the file, it returns a file reference number. We set this reference number to the variable f (for file) so that we can more easily reference our file later on.

In Line 2, we tell AppleScript to write the text “This is a test” to our file.

In Line 3, we close access to our file. You should always explicitly close access to any open files or you may have trouble later.

To read data from a file, we simply tell AppleScript to read from our file:

read file ((path to desktop as text) & "test.txt")

There you have it. You can now read and write data to files. Please note that this is most effective for text files, including XML files, but not binary files such as Word files. We’ll explore how to read and write Word files and other binary files in later lessons.

In rb-appscript, we can avoid the use of these commands altogether because Ruby has its own File class to deal with file objects. Please read the documentation for the Ruby File class to learn how to read from and write to files in Ruby.

Leave a Reply