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.

0 comments:

Post a Comment