Need Some Help? Have a Tip to Share?

Email me at MacTipper@gmail.com, or, leave a comment!

Subscribe To Our FREE RSS Feed!

Don't miss out on any posts from the Concise MacTipper Blog.

Monday, May 11, 2009

Read and Write Text Files Using AppleScript

AppleScript includes some functions to allow you to manipulate text files. To read a text file, just use:

set the_file to "Crocs:Users:oliver:Desktop:Err.txt" as alias

open for access the_file
set the_text to read the_file
close access the_file
return the_text


To write to a text file (by default, at the beginning) you can use:

set the_file to "Crocs:Users:oliver:Desktop:Err.txt" as alias

open for access the_file with write permission
write the_text to the_file
close access the_file
return the_text


If you want to write to the end of the text file use:

write the_text to the_file starting at eof


("eof" stands for "end of file".)

Finally, I've written this simple AppleScript subroutine to act as a substitute for the "echo" shell script command:

on write_file(the_file, the_info, overwrite_contents)
try
close access the_file
end try
set opened_file to open for access the_file with write permission
if overwrite_contents is true then set eof of opened_file to 0
write the_info to the_file starting at eof
close access the_file
end write_file

on run
write_file((choose file), (return & "Hello"), false)
end run


Using that, you can specify where to write, what to write, and whether or not to overwrite the original file.

4 comments:

  1. Concise indeed, and just what I was looking for. Thanks!
    ReplyDelete
  2. A couple of errors in write file, should be

    on write_file(the_file, the_info, overwrite_contents)
    try
    close access the_file
    end try
    set opened_file to open for access the_file with write permission
    if overwrite_contents is true then set eof of opened_file to 0
    write the_info to opened_file starting at eof
    close access opened_file
    end write_file
    ReplyDelete
  3. I want to read a txt (textedit) file from my desktop, but when i run the following program :

    set the_file to "/Users//Desktop/Bookmarks.txt" as alias

    open for access the_file
    set the_text to read the_file
    close access the_file
    return the_text

    I get the following error message:

    File /Users//Desktop/Bookmarks.txt wasn’t found.

    I checked the location of the Bookmarks.txt, and it said:

    /Users/JoshuaWensley/Desktop

    Can anyone tell me what i've done wrong?
    ReplyDelete
    Replies
    1. It has to be like this
      Users:JoshuaWensley:Desktop:Bookmarks.txt
      Delete