Want to create a text file and write to the file

I’m new to AppleScript and am having trouble. I want to write to a text file but after searching for the information am unable to do it. Anybody able to provide me with some insight? Thanks.

This should get you started:

tell application “Finder”
make new file at desktop with properties {name:“foo.txt”}
end tell

set out_file to “Macintosh HD:Users:username:Desktop:foo.txt”
Open the output file
open for access file out_file with write permission
reset the eof
set eof of the (out_file as alias) to 0
The file will be overwritten each time the script is run
Comment out this line if you want text to be
appended rather than overwritten

Now get the text to add to the file
display dialog “Please enter the text to write in the file” default answer “”
set the_text to the text returned of the result
write the_text to the (out_file as alias) starting at eof
close access the (out_file as alias)

this script was automatically tagged for
color coded syntax by Script to Markup Code
written by Jonathan Nathan


Here’s the routine that I generally use (more info). The script will generate a file named “XXXX Sample Text File XXXX.txt” on the desktop.

set desktop_ to path to desktop as Unicode text
write_to_file("some text for the file", (desktop_ & "XXXX Sample Text File XXXX.txt"), false)

-- Include, but do not modify, the code below this line
to write_to_file(this_data, target_file, append_data)
		set the target_file to the target_file as text
		set the open_target_file to ¬
			open for access file target_file with write permission
		if append_data is false then ¬
			set eof of the open_target_file to 0
		write this_data to the open_target_file starting at eof
		close access the open_target_file
		return true
	on error
			close access file target_file
		end try
		return false
	end try
end write_to_file

– Rob


Thanks for posting this. Your solution is more robust and less error prone than mine. When ever I am working on scripts that open files and work on them, I always end up with a bunch of open test files that I can’t delete because the script opened them and died before it closed them.

Thanks again!



In the name of full disclosure, the handler is one of Apple’s Essential Sub-Routines. With that said, I’m glad it was helpful. I hope that cma007 can understand and use it. :slight_smile:

– Rob