I'm trying to write content to a file, /tmp/test.txt with AppleScript.
- If the file doesn't exist, I want to create it.
- If it does exist, I want to replace the contents.
This is proving quite difficult because AppleScript has a different syntax for creating a new file versus writing to an existing file. I also thought about deleting a file if it already exists, and then creating it, but AppleScript will move things to the trash by default and so even that is rather complicated.
The data I am going to write to the file may have a lot of special characters in it, so I don't really want to do something like do shell script "cat " + data + " > /tmp/txt.txt" because I am unaware of any escapeshellarg for AppleScript.
Below is what I have so far but I'm getting an error:
Can't make file "Macintosh HD:private:tmp:test.txt" into type reference.
I would really like to abstract this by improving the helper function write_to_file that I got here so that it would take care of creating the file if it does not exist.
my write_to_file("hello", "/tmp/test.txt", false)
on write_to_file(this_data, target_file, append_data)
try
if not (exists POSIX file target_file) then
make new document file at ("/tmp/" as POSIX file as alias) with properties {name:"test.txt", text:the_data}
end if
set the target_file to the target_file as POSIX file
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 e
try
display dialog e
close access file target_file
end try
return false
end try
end write_to_file