So I am trying to create a simple script that will use a file to store an integer. When the script is called (in my case as part of a keyboard macro) it will drop in (where I'm typing) the current integer, with the requisite number of leading zeros. Then it will increment the integer (without the leading zeros) and write it back into the file.

The leading zeros part works, but for the life of me I can not figure out how to store the value of the 'counter' variable in a file so that, later, when I call the script again, it will pick up where it left off.

Any help would be greatly appreciated.

Here is the error message I get:

    error "Can’t make \"z:Users:zachphillips:Dev:AppleScripts:counter\"  
    into type file." number -1700 from
    "z:Users:zachphillips:Dev:AppleScripts:counter" to file

And here is the code:

    set theFile to "z:Users:zachphillips:Dev:AppleScripts:counter"
        open for access theFile
        set fileContents to read theFile
        close access theFile

        set counter to fileContents as integer

        on add_leading_zeros(counter, max_leading_zeros)
        set the threshold_number to (10 ^ max_leading_zeros) as integer
        if counter is less than the threshold_number then
            set the leading_zeros to ""
            set the digit_count to the length of ((counter div 1) as string)
            set the character_count to (max_leading_zeros + 1) - digit_count
            repeat character_count times
                set the leading_zeros to (the leading_zeros & "0") as string
            end repeat
            return (leading_zeros & (counter as text)) as string
            return counter as text
        end if
    end add_leading_zeros

    add_leading_zeros(counter, 2)

    open for access newFile with write permission
    set eof of newFile to 0
    write counter + 1 to newFile
    close access newFile

Add a .txt extension to the file you're saving to. If counter is the folder, do this:

set theFile to "z:Users:zachphillips:Dev:AppleScripts:counter:save.txt"

Assuming that you have a valid path, this should fix the problem. Otherwise, you're trying to save to a folder.


The result of open for access is a "file reference number". You must use this number with the read, write, and close access commands. For example,

set handle to open for access theFile
set fileContents to read handle
close access handle

Also, the script ignores the result of add_leading_zeros(counter, 2). You can put the result back in counter with

set counter to add_leading_zeros(counter, 2)

but if you do counter + 1 after that, AppleScript coerces counter from text to integer, and you lose the leading zeros. You want to add 1 before you put the leading zeros, like

set counter to add_leading_zeros(counter + 1, 2)

You must log in to answer this question.