Reputation: 1747
I am AppleScript nub and I am moments away from buying a type writer and moving into the mountains.
Can anyone, please, explain to me why this fails:
set mah_file to POSIX file "/Users/me/folder/fileinfo.txt"
set mah_data to "some text!!!!!!"
on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
try
set the target_file to the target_file as text
set the open_target_file to ¬
open for access file of 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
try
close access file target_file
end try
return false
end try
end write_to_file
write_to_file(mah_data, mah_file, true)
Even though this succeeds:
set mah_file to choose file
set mah_data to "some text!!!"
-- the rest is identical
I've tried:
set mah_file to POSIX file "/Users/me/folder/fileinfo.txt" as file
and
set mah_file to POSIX file "/Users/me/folder/fileinfo.txt" as alias
and
set mah_file to POSIX file "/Users/me/folder/fileinfo.txt" as text
And since AppleScript can't be bothered to tell me why this isn't working, I am well and truly losing my mind.
Upvotes: 0
Views: 1674
Reputation: 89
You can use the echo command in combination with >> to write text to a file
if the textile doesn t exist a new one will be created
if the text file already exists and
you use > you can override an existing textile with the same name
you use >> the text will be added to the existing file
set mypath to "/Users/" & (short user name of (system info)) & "/Desktop/file.txt" as string
set myText to "text to write in the text file" as string
do shell script "echo " & "\"" & myText & "\"" & ">>" & mypath
and mypath is and POSIX path
hope that is what you was searching for
Upvotes: 1
Reputation: 27633
read
and write
also use the primary encoding (like MacRoman or MacJapanese) by default. Add as «class utf8»
to preserve non-ASCII characters in UTF-8 files.
Writing:
set b to open for access "/tmp/1" with write permission
set eof b to 0
write "α" to b as «class utf8»
close access b
Appending:
set b to open for access "/tmp/1" with write permission
write "ア" to b as «class utf8» starting at eof
close access b
Reading:
read "/usr/share/dict/connectives" as «class utf8»
Upvotes: 1
Reputation: 1902
Leave out the file
and POSIX file
keywords:
set mah_file to "/Users/me/folder/fileinfo.txt"
...
set the open_target_file to open for access mah_file with write permission
Upvotes: 3