AppleScript: read and write text files
Main topics: ResourcesMacGuides
Argomenti: Applescript
Author: Marco Balestra
When starting with programming one of the firt issue is the access to text files.
Let’s see how to do it using AppleScript.
Use the Unix subsytem to read a text file
The easiest way for reading a simple text file is to do it through Unix:
Obviousley this isn’t the smartest way, in any case we could always consider it.
Other ways, more AppleScriptish, follow.
Use AppleScript to read a text file
The main way is “open for access”:
"open for access" requires a reference to a Finder file, and this is exactly wath we get when using "POSIX file unixPath
".
This sintax works fine... but only reads text files encoded “Mac Roman”, while often we needto access Unicode (UTF-8 or UTF-16) files.
Read a UTF-16 encoded text file:
Read a UTF-8 encoded text file:
Every paragraph of a text
Split a text variable in a list containing one line per entry is quite simple:
Of course the variable listVariable isn’t linked to the original text, by the way after changing it we can easily rebuild the entire text in a single variable:
Search and Replace
AppleScript doesn’t support regular expressions (not out-of-the-box, language modules could extend it), but there’s a simple way for searching and replacing static values in a string:
I know, it sounds weird the first time you look at it…
On the other hand it’s fast and very affordable.