7.5. Reading and Writing Files

Now that you know all about path names, POSIX path names, and aliases, it's time to learn how to perform some basic operations with files. You start by learning how you create a file, write some data to it, and subsequently read it back to verify its contents.

To perform I/O operations on a file in AppleScript, you can follow these three steps:

  1. Open the file using the open for access command. This command returns a number that you use to subsequently identify the file for any I/O operations you perform on the file.

  2. Read data from the open file using the read command. You write data to the open file using the write command.

  3. Close the file using the close access command.

The next Try It Out helps you begin manipulating files in AppleScript. You create a sample text file called TextFile101 in your Documents directory and use this file in examples throughout this chapter.

You may want to ensure that you don't already have a file by that name in your Documents folder. If you have one, you may want to rename it so that it isn't overwritten by the file you create next.

7.5.1.

7.5.1.1. Try It Out: Creating a File in AppleScript

In the following steps, you type a program that creates a new file in AppleScript.

  1. Type the following program into Script Editor:

    -- Create a sample file in the user's Document folder
    
    -- create the file name
    
    set fileName to (path to documents folder as string) & "TextFile101.txt"
    
    -- open the file for write access set fileID to open ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.