How can I read/write a file?

Apple’s Standard Additions provide a Suite to read and write files, aka “File Read/Write” or “Read/Write commands”.

You can read a file with this simple line of code:

set fileContents to (read alias "path:to:file.txt")

If you explore the dictionary, you will find lots of possibilities: read only the first 1000 bytes of a file, read using a delimiter, etc.

Writing to a file could get more difficult, but you can find lots of code online showing you the better approach. This is a sample:

set fileRef to (open for access file "path:to:file.txt" with write permission)
--> this will return a "reference number", which is similar to a stream,
--> or just as the ticket you need to ride through the bytes

--> the following will delete the contents of the file
set eof of fileRef to 0

write "this is a test" to fileRef
close access fileRef
--> this has closed the "way" we opened previously using the "open for access" command

Explore the dictionary and you’ll find more parameters: start writing at a specified byte, write as list or record data, etc.