Writing to File

Often scripts will be designed to write data to files such as logs or backups. The following routine can be used to safely write data to disk. It is designed to work with TEXT files and if there is no existing file, will create one as needed.

The sub-routine requires a file path for the target file, the data to write, and a value of true or false for whether the data should be appended to existing data.

The following example script will use the sub-routine on this page to create a file on the desktop named "MY STORY" containing the passed data. If the file already exists, the script will replace the current contents of the file with the passed data.

set this_story to "Once upon a time in Silicon Valley..."
set this_file to (((path to desktop folder) as string) & "MY STORY")
my write_to_file(this_story, this_file, false)

The following example script will use the same sub-routine to append an entry to a log file on the desktop:

set this_data to ((current date) as string) & space & "STATUS OK" & return
set this_file to (((path to desktop folder) as string) & "MY LOG FILE")
my write_to_file(this_data, this_file, true)

Here's the sub-routine:

Click to open example in the Script Editor applicationA sub-routine for writing data to a file:

on write_to_file(this_data, target_file, append_data)
 set the target_file to the target_file as string
 set the open_target_file to open for access file target_file with write permission
 if append_data is false then set eof of the open_target_file to 0
 write this_data to the open_target_file starting at eof
 close access the open_target_file
 return true
 on error
 close access file target_file
 end try
 return false
 end try
end write_to_file

The following error handler can be used in conjunction with the sub-routine to keep a log errors occurring during the execution of a script. Be sure to include the sub-routine above when adding it to your scripts:

Click to open example in the Script Editor applicationAn error handler that calls the sub-routine to append the error message to a log file:

on error error_message number error_number
 set this_error to "Error: " & error_number & ". " & error_message & return
 -- change the following line to the name and location desired
 set the log_file to ((path to desktop) as string) & "Script Error Log"
 my write_to_file(this_error, log_file, true)
end try