Name

close access — close file

Description

Closes a file. Always close a file you have opened for access.

In general, the file data commands are smart about how they let you describe the file you want to operate on: they can take a file reference number returned by open for access, or a file specifier or alias.

When using the file data commands, you should ensure sufficient error handling so as not to leave a file open. If you do accidentally leave a file open, you might have to quit the current application (such as the Script Editor) in order to close it.

In this example, we use AppleScript to construct a miniature “database.” We have some strings; taking advantage of the write command’s starting at parameter, we write each string into a 32-character “field.” The example perhaps overdoes the error handling, but it shows the general idea:

set pep to {"Mannie", "Moe", "Jack"}
set f to (path to current user folder as string) & "testFile"
try
        set fNum to open for access file f with write permission
on error
        close access file f
        return
end try
try
        set eof fNum to 0 -- erase if exists
        set eof fNum to (count pep) * 32
        repeat with i from 1 to (count pep)
                write item i of pep to fNum starting at (i - 1) * 32
        end repeat
        close access fNum
on error
        close access fNum
end try

Now we’ll fetch the data from the “database.” We take advantage of the fact that all data that isn’t part of a string is null.

set f to choose file of type "TEXT" try set fNum to open for access f on error close access f return ...

Get AppleScript: The Definitive Guide 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.