Io 如何使用AppleScript写入文本文件?

Io 如何使用AppleScript写入文本文件?,io,applescript,Io,Applescript,就这样。如何使用AppleScript写入文本文件 我试着在谷歌上搜索,但答案似乎已经过时了,我也不确定现在最喜欢的成语应该是什么 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_targ

就这样。如何使用AppleScript写入文本文件

我试着在谷歌上搜索,但答案似乎已经过时了,我也不确定现在最喜欢的成语应该是什么

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 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
与它的接口可以通过以下方式清理

my WriteLog("Once upon a time in Silicon Valley...")

on WriteLog(the_text)
    set this_story to the_text
    set this_file to (((path to desktop folder) as text) & "MY STORY")
    my write_to_file(this_story, this_file, true)
end WriteLog

我还了解到,如果一个人只想向一个文件中吐出一点文本,那么快速破解就是使用shell

do shell script "echo TEXT > some_file.txt"

对我来说,在PowerBook G4上运行do shell脚本在循环中执行300000次时速度太慢;),但当然,这样写起来更快,有时也有意义。您还需要像这样转义shell字符:

执行shell脚本“echo”&引用foobar的形式&“>>some_file.txt”

出于美学原因,我会使用

告诉我做shell脚本“#…”


但我还没有证实(我相信的)如果“DoShell脚本”在一个“tell Finder”块中,例如,是Finder进程创建了一个子shell。有了“告诉我做shell脚本”,至少脚本编辑器日志看起来更适合我

纯AppleScript的简短版本:

set myFile to open for access (choose file name) with write permission
write "hello world" to myFile
close access myFile
似乎没有本机的单命令解决方案。相反,您必须打开并随后关闭该文件。

@JuanANavarro

使用shell时,文本和文件路径应使用的引号形式。 这将有助于阻止文件名中带有空格和字符(例如文本中的撇号)的错误

set someText to "I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell."

set textFile to "/Users/USERNAME/Desktop/foo.txt"
do shell script "echo  " & quoted form of someText & " >  " & quoted form of textFile
上面的脚本很好用


如果我没有某个文本的引用形式

但是相反,我有&someText,我会得到以下错误

错误“sh:-c:第0行:在查找匹配项“”时出现意外EOF”

sh:-c:第1行:语法错误:文件“编号2”意外结束

我已经”中的撇号被视为命令的一部分


如果我有

将textFile设置为“/Users/USERNAME/Desktop/some foo.txt”作为我的文件路径(注意空格),并且没有引用形式的textFile,而是我有&textFile


然后,当文件被写入时,它将写入一个名为“some”的文件,而不是“some foo.txt

的文件。请查看与此相关的我的答案。如果
TEXT
包含
“$()“!
和其他一些。您必须告诉Applescript先使用
的引号形式引用文本。我发现此版本无法将非ASCII字符写入文本文件。是否有此代码的UTF-8兼容版本?在生成的文本文件中,非ASCII字符显示为“”。这是文件IO的一个很好的解决方案灵活性是因为文件IO镜像了经典MacOS中的调用,例如来自文件管理器的旧
FSRead
FSWrite
调用。您需要为打开的文件设置
FSRef
,然后设置EOF以在开始编写之前清除文件。@kakyo,要使其与utf8兼容,请将
添加为«类utf8»
在第8行,将此数据写入打开的目标文件(从eof开始为«class utf8»
我相信如果文件已经存在并且比现在写入的文件更长,则此操作不会像预期的那样起作用-然后旧数据仍保留在文件中。要解决此问题,请首先使用
将myFile的eof设置为0来擦除内容如接受的答案所示