在Applescript中写入文件 - 无法正常工作

时间:2011-11-15 18:21:05

标签: file applescript

我一直在尝试将文件写入xmlhttp GET请求的结果。我尝试过以下代码:

set the_file to "/Users/xxxx/Documents/outputvals.txt" as file specification

set the_data to costItems

try
    open for access the_file with write permission
set eof of the_file to 0
write (the_data) to the_file starting at eof as list
close access the_file
end try

但它似乎没有写任何文件。理想情况下,我想将xml'costItems'写入文本文件的末尾。

1 个答案:

答案 0 :(得分:0)

通常,如果您要对文件或文件夹执行任何操作,则必须是完整的alias引用。只需将as file specification更改为as POSIX file as alias,该部分即可使用!

此外,删除as list并删除行set eof of the_file to 0。假设文件已包含信息,您基本上告诉脚本文件的末尾是文件的开头。

我希望这有帮助!

编辑:我不知道为什么你的代码不能正常工作(它适合我)。好吧,我想你可以试试以下(虽然有点hacky,但是哦,好吧:P)

tell application "Finder"
    try
        set the_file to "/Users/xxxx/Documents/outputvals.txt" as POSIX file as alias
    on error --file doesn't exist yet, so create it
        set the_file to (make new document file at ("/Users/xxxx/Documents/" as POSIX file as alias) with properties {name:"outputvals", text:""}) 
        --Normally, when you're creating documents in this fashion, you would put the text you want in the document after the 'text' property, but for your sake I will use the alternative :)
    end try
end tell
set the_data to costItems
try
    open for access the_file with write permission
    write the_data to file the_file starting at eof
    close access the_file
on error --you never know when errors will crop up (when it comes to reading and writing files); better to be safe than sorry
    try
        close access the_file
    end try
end try