Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.