Thursday, March 30, 2017

#1 2005-10-12 03:06:40 pm

julifos
Administrator
From: MalasaƱa, Madrid
Registered: 2002-11-20
Posts: 2014

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:

Applescript:

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:

Applescript:

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.

Offline

 

Board footer

Powered by FluxBB

[ Generated in 0.131 seconds, 10 queries executed ]

RSS (new topics) RSS (active topics)