AppleScript:尝试在文本编辑文件中写入

AppleScript:尝试在文本编辑文件中写入,applescript,textedit,Applescript,Textedit,我正在尝试写入已创建的文本编辑文件。 该文件处于RWX模式,因此没有权限问题 但当我执行代码时,以下是错误: error "Network file permission error." number -5000 from file "/Users/me/Desktop/A directory/file.txt" to «class fsrf» 我的代码在这里: -- Writing in the TextEdit file set file_URLs_content to "HEEEELLO

我正在尝试写入已创建的文本编辑文件。 该文件处于RWX模式,因此没有权限问题

但当我执行代码时,以下是错误:

error "Network file permission error." number -5000 from file "/Users/me/Desktop/A directory/file.txt" to «class fsrf»
我的代码在这里:

-- Writing in the TextEdit file
set file_URLs_content to "HEEEELLOOOOOO"
tell application "TextEdit"
    set theFile to "/Users/me/Desktop/A directory/file.txt"
    set file_ref to (open for access file theFile with write permission)
    set eof file_ref to 0
    write file_URLs_content to file_ref
    close access file_ref
end tell

而且我的file.txt仍然是空的,我如何避免这个错误?

你不需要文本编辑。试试这个:

set the logFile to ((path to desktop) as text) & "log.txt"
set the logText to "This is a text that should be written into the file"
try
    open for access file the logFile with write permission
    write (logText & return) to file the logFile starting at eof
    close access file the logFile
on error
    try
        close access file the logFile
    end try
end try
尝试:


使用TextEdit编写文本时避免错误的方法是记住它是一个文本编辑器。它已经知道如何创建和保存文本文档而不产生错误。您不必使用(容易出错的)open for access。您不必使用(容易出错的)shell脚本。你所要做的就是让TextEdit为你制作一个包含你喜欢的任何内容的文本文档,并将其保存到你喜欢的任何地方。TextEdit知道如何在不产生文件访问错误(如open for access)或意外覆盖文件夹(如shell脚本)的情况下执行此操作

此方法的优点是编写速度更快、更容易,不易出错,作为输出获得的文本文件与使用TextEdit手动创建的文本文件具有相同的属性,并且您的脚本现在可以轻松扩展以包含其他应用程序。例如,文本内容可能来自另一个应用程序或剪贴板,文本文件可以在另一个应用程序中打开或在保存后通过电子邮件发送

AppleScript最基本的功能是以这种方式向Mac应用程序发送消息。如果要将PNG转换为JPEG,则不要在AppleScript中编写PNG解码器和JPEG编码器,然后打开PNG文件进行访问,逐字节读取,然后逐字节编码JPEG。您只需告诉Photoshop打开PNG图像并将其作为JPEG导出到特定的文件位置。“open for access”命令是读取和写入您根本没有应用程序可读取或写入的文件的最后手段。“do shell script”命令用于在没有Mac应用程序来完成任务时合并命令行应用程序,例如,您可以使用Perl执行regex操作。如果你所做的只是处理文本文件,那么你不仅可以使用TextEdit,还可以从Mac App Store获得免费的TextWrangler,它还有一个巨大的AppleScript字典,用于读取、写入和编辑文本文件

set file_URLs_content to "HEEEELLOOOOOO"
set filePath to POSIX path of (path to desktop as text) & "file.txt"
do shell script "echo " & quoted form of file_URLs_content & " > " & quoted form of filePath
tell application "TextEdit"
    activate
    set theDesktopPath to the path to the desktop folder as text
    set file_URLs_content to "HEEEELLOOOOOO"
    make new document with properties {text:file_URLs_content}
    save document 1 in file (theDesktopPath & "file.txt")
    close document 1
end tell