25

So, that's it. How can I write to a text file using AppleScript?

I've tried googling around, but answers seem to be years old and I'm not really sure what should be the preferred idiom this days.

Juan A. Navarro
  • 10,595
  • 6
  • 48
  • 52

5 Answers5

31
on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
    try
        set the target_file to the target_file as text
        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
        try
            close access file target_file
        end try
        return false
    end try
end write_to_file

Interfacing with it can be cleaned up with the following...

my WriteLog("Once upon a time in Silicon Valley...")

on WriteLog(the_text)
    set this_story to the_text
    set this_file to (((path to desktop folder) as text) & "MY STORY")
    my write_to_file(this_story, this_file, true)
end WriteLog
Philip Regan
  • 5,005
  • 2
  • 25
  • 39
  • 1
    I found this version unable to write non-ASCII characters to text files. Is there an UTF-8 compatible version of this code? The non-ASCII characters appear as ?? in the resulting text files. – kakyo Feb 22 '15 at 03:42
  • This a good solution for file IO, the complexity is because the file IO mirrors the calls in classic MacOS, eg the old `FSRead` `FSWrite` calls from File Manager. You need to have a `FSRef` for the file you open and then set the EOF to clear the file before you begin writing. – Michael Shopsin Oct 29 '15 at 21:00
  • 5
    @kakyo, to make it utf8 compatible, add `as «class utf8»` to the code on line 8 so it becomes `to write this_data to the open_target_file starting at eof as «class utf8»` – user65535 Dec 13 '18 at 04:42
12

A short version in pure AppleScript:

set myFile to open for access (choose file name) with write permission
write "hello world" to myFile
close access myFile

It seems there is no native one command solution. Instead you have to open and later close the file.

flori
  • 14,339
  • 4
  • 56
  • 63
  • I believe this does not work as expected if the file already exists and was longer then what's being written now - then old data remains in the file. to solve this, you'd first erase the contents with `set eof of the myFile to 0` as shown in the accepted answer – Thomas Tempelmann Feb 24 '18 at 00:00
10

@JuanANavarro.

When using the shell you should use quoted form of for the TEXT and the file path. This will help stop errors with spaces in file names and characters like apostrophes in the text for example.

set someText to "I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell."

set textFile to "/Users/USERNAME/Desktop/foo.txt"
do shell script "echo  " & quoted form of someText & " >  " & quoted form of textFile

The above script works fine.


If I did not have & quoted form of someText

but instead I had & someText I would get the following error.

error "sh: -c: line 0: unexpected EOF while looking for matching `''

sh: -c: line 1: syntax error: unexpected end of file" number 2

The apostrophes in "I've" is seen as part of the command.


If I had

set textFile to "/Users/USERNAME/Desktop/some foo.txt" as my file path ( note the space.) And did not have & quoted form of textFile but instead I had & textFile

Then when the file was written out it would write to a file named "some" and not "some foo.txt"

Community
  • 1
  • 1
markhunte
  • 6,805
  • 2
  • 25
  • 44
8

I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell.

do shell script "echo TEXT > some_file.txt"
Juan A. Navarro
  • 10,595
  • 6
  • 48
  • 52
  • 3
    Please see my answer relating to this. – markhunte May 11 '14 at 21:37
  • 1
    Will fail if `TEXT` contains characters like `"$()'!` and some others. You you must tell Applescript to quote the text first by using `quoted form of` – Mecki Nov 06 '18 at 12:44
4

For me running do shell script was too slow on a PowerBook G4 when executed in a loop 300000 times ;), but of course that's quicker to write which sometimes makes sense. You would also want to escape shell characters like this:

do shell script "echo " & quoted form of foobar & " >> some_file.txt"

and for aesthetic reasons I would use

tell me to do shell script "#..."

but I haven't verified yet (what I believe) that if "do shell script" is in a block of "tell Finder" for example it is Finder process that creates a subshell. With "tell me to do shell script" at least Script Editor log looks better for me. ;)

Zygmunt
  • 281
  • 1
  • 6