Write to file

Hi

I need to generate file name from few strings and then write something to that file.
File itself also should be created by script.

How can I do this?

Thank you.

It would be nice also if I could use posix path for file.

Simple example:


set filepath to "/Users/martin/Desktop/foo.bar"
set foo to "bar"

try
	set openfile to open for access (POSIX file filepath) with write permission
	write foo to openfile
	close access openfile
on error
	try
		close access openfile
	end try
end try

set thefolder to "your:path:to:folder:" as string
set thefilepath to (thefolder & string1 & ":" & string2) as string
open for access thefilepath with write permission
set thefile to thefilepath as alias
--if you want to write put similar to this here:
--write thewritingstring to thefile
close access thefile

Hi Richard,

It’s better scripting habit to use the file pointer, which is the result of the open for access line.
Based on Martin’s example this is the most reliable syntax


set filepath to ((path to desktop as text) & "foo.bar")
set foo to "bar"

try
	set openfile to open for access file filepath with write permission
	write foo to openfile
	close access openfile
on error
	try
		close file filepath
	end try
end try

BTW: as AppleScript has an unique text class text since 10.5, the coercion as string is deprecated.
And it’s actually useless in the first two lines of your example, because a literal string and a concatenation of strings is text anyway

I usually go on the safe side because it’s easier than going back if I had a non string, especially with ASOC.

Maybe this is necessary in ASOC, in plain AppleScript you have a bunch of overload with useless coercions.

In my opinion the lack of “toll-free-bridging” classes AppleScript <–> Cocoa is very lousy implementation!