Very newbie question: How to read from and write to file???

Hi, this is a very newbie question.

In AppleScript Studio I’m trying to learn how to read from and write to a file residing in a given path , but I just can’t get it right - I’ve learnt how to do this in AppleScript, but obviously the syntax wasn’t the same in the Studio.

 write ((variable - 1) as text) to file "Volumes:path:file.txt"
set variable to (read from file ("/Volume/path/file.txt"))

AppleScript Error: Disk Volumes:path:file.txt wasn’t found. (-35)

I’ve tried the documentation, but I couldn’t find quite what I’m looking for.
Is it so incredibly difficult to read and write to a file with a fixed path in ASStudio, or am I just plain stupid? :shock:
…please don’t answer that last question!

Just to mention; I’ve also tried separating the directores and file with slashes, but that didn’t do me no good either…




I use this:

writeTo("diskname:dir:subdir:file.txt", "blah", string)
to writeTo(f, stuff, |mode|)
	set f to f as Unicode text
	if f does not contain ":" then set f to POSIX file f as Unicode text
	set fRef to (open for access file f with write permission)
		set eof of fRef to 0
		write stuff to fRef as |mode|
		close access fRef
	on error msg number n
			close access fRef
		end try
		error msg number n
	end try
	alias f
end writeTo

You can pass a simple path (“path:to:file”), an alias (alias “path:to:file”), file specification (file “path:to:file”) or POSIX path (“/to/file”). It will overwrite the previous contents of the related file, and will write the data as you specify (eg, string, real, record, picture, «class utf8», etc.).
Regarding your original question, “write” doesn’t accept POSIX paths (“/blah/blah”), but mac-style paths (separators = colons) specified as simple paths, file references or aliases.
If the file already exists, you can use “write” as follow:

write "foo" to "path:to:file.txt"

If the previous contents of “file.txt” were “blah”, the contents will be after executing this sentence “fooh” (that is, it overwrites the original contents without first emptying the file).
“read” will accept the same kind of input (so, no POSIX paths), and you don’t need opening the file for access:

read "path:to:file.txt"

This will read file’s contents as string by default (as well as “write” writes as string, by default), and you could also specify (eg) “as record”, if you previously wrote a record to the file; this way, you will hold a record in your hands, instead of a bunch of text.