问题
I'm having trouble figuring out how to properly use "write" in applescript. I currently have code like this:
set randomArray to {"hello", "text", "file"}
set saveFile to (path to desktop as text) & "RandomFile.txt"
write randomArray to saveFile starting at eof as list
I know that this is not right, but I can't seem to figure out what the correct thing to put where "saveFile" is would be.
Any help is appreciated, thanks :)
回答1:
A good example to write to a file can be found in the code-snippet (CTRL-Click into a script to see them) Error Handlers
, Write Error to Log
.
To save an array/list you can use something like this:
set randomArray to {"hello", "text", "file"}
set fullText to ""
repeat with i from 1 to number of items in randomArray
set thisItem to item i of randomArray
set fullText to fullText & thisItem
if i is not number of items in randomArray then set fullText to fullText & return
end repeat
my scriptLog(fullText)
on scriptLog(thisText)
set the logFilePath to ((path to desktop) as text) & "Script Log.txt"
try
open for access file the logFilePath with write permission
write (thisText & return) to file the logFilePath starting at eof
close access file the logFilePath
on error
try
close access file the logFilePath
end try
end try
end scriptLog
回答2:
As zero mentioned you need to open the file before writing into it. After writing you have to close the access. BTW reading a whole file is possible with one call of the read handler. Another point in your question is that you want to write a list. This is possible of course, but you'll need to read the content as list, too. Putting all together and taking the main points from zero's answer, we get this:
set randomArray to {"hello", "text", "file"}
set saveFile to (path to desktop as text) & "RandomFile.txt"
-- write the file
set theFilehandle to open for access file saveFile with write permission
write (randomArray) to theFilehandle starting at eof as list
close access theFilehandle
-- read the file
read file saveFile as list
Enjoy, Michael / Hamburg
来源:https://stackoverflow.com/questions/29733898/how-do-you-properly-use-write-in-applescript