wyvern-eater

Q: How to close all files that an Applescript has opened?

I'm writing a script with multiple "open for access file ... with write permission" commands. It writes to various of them, making csv databases as it works its way through analyzing an xml file (generated by other software), then closes them all at the end.

 

My problem is that, if the script crashes or I have to halt it before it gets to the "close" commands at the end, the files are left open. This causes an obvious error when next running the script after making adjustments.

 

How can I ensure that those files are always closed? At present I'm doing it by quitting and re-starting Script Editor, which leaves me disoriented in the code.

 

Is there a generic close command that I can insert at the start of the script, for example?

Posted on Aug 31, 2012 12:21 PM

Close

Q: How to close all files that an Applescript has opened?

  • All replies
  • Helpful answers

  • by twtwtw,Solvedanswer

    twtwtw twtwtw Aug 31, 2012 12:50 PM in response to wyvern-eater
    Level 5 (4,935 points)
    Aug 31, 2012 12:50 PM in response to wyvern-eater

    Use this handler to open files.  It tries to open the file, and if it gets error -49 (file already open) it closes the file and reopens it.  It returns a file pointer to the open file, which you can use to refer to the file later.

     

    on openAFile(filePath, writable)

              try

                        set fp to open for access filePath write permission writable

              on error errstr number errNum

                        if errNum = -49 then

                                  close access filePath

                                  set fp to open for access filePath write permission writable

                        else

                                  display dialog errstr

                                  return false

                        end if

              end try

              return fp

    end openAFile

     

    set pointer to openAFile("/path/to/some/file", true)

    set fileContents to read pointer

    --close access pointer

  • by wyvern-eater,

    wyvern-eater wyvern-eater Aug 31, 2012 12:58 PM in response to twtwtw
    Level 1 (14 points)
    Notebooks
    Aug 31, 2012 12:58 PM in response to twtwtw

    Excellent, and obvious once pointed out.  Thank you!