AppleScript 无法保存文本编辑文件

AppleScript cannot save a textedit file

我正在使用代码为实验室数据格式化 textedit 文件。

我目前正在使用 AppleScript 在 TextEdit 中创建文档并向其中添加文本,但是当我尝试保存它时,TextEdit 给我错误消息“您没有另存为 blahblahblah 的权限。”我已经尝试更改我保存它的文件夹的权限,但我认为这可能与它是 AppleScript 创建的文件有关。

确切的错误输出是来自 TextEdit 的对话框

The document “1.txt” could not be saved as “1”. You don’t have permission.

To view or change permissions, select the item in the Finder and choose File > Get Info.

我的代码段不起作用是

tell application "TextEdit"
    make new document with properties {name:("1.txt")}
end tell


--data formatting code here (n is set here)


tell application "TextEdit"
    delay 1
        
    close document 1 saving in ("/Users/bo/Desktop/Script Doc/" & (n as string))
    
    set n to n + 1
    make new document with properties {name:((n as string) & ".txt")}
    delay 1
end tell

我搜索了其他问题,找到了代码段

open for access document 1
close access document 1

但我不确定如何实施这些/如果我应该实施,如果不实施,我不确定如何解决这个问题。

提前致谢

不幸的是,该错误消息没有多大帮助。您实际上是在尝试保存到一个字符串中,这是行不通的 - 您需要使用 文件说明符 ,例如:

close document 1 saving in POSIX file ("/Users/bo/Desktop/Script Doc/" & n & ".txt")

请注意,并非所有内容都知道 POSIX 路径,在这种情况下,您需要像我的示例一样强制或指定它。

TextEdit 已被沙盒化。您无法将文档保存在标准桌面文件夹中。

另一种方法是将路径硬编码到 TextEdit 容器中的文档文件夹。

tell application "TextEdit"
    make new document with properties {name:"1.txt"}
end tell


set containerDocumentsFolder to (path to library folder from user domain as text) & "Containers:com.apple.TextEdit:Data:Documents:"
tell application "TextEdit"

    close document 1 saving in containerDocumentsFolder & (n as string) & ".txt"

    set n to n + 1
    make new document with properties {name:(n as string) & ".txt"}
end tell

使用最新版本的 macOS Mojave 可以直接保存到桌面

property outputPath : POSIX path of (((path to desktop as text) & "Script Doc") as alias)
property docNumber : 1
property docExtension : ".txt"

tell application "TextEdit"
    set docName to (docNumber & docExtension) as text
    set theText to "Your Desired Text Content"

    set thisDoc to make new document with properties {name:docName, text:theText}
    close thisDoc saving in POSIX file (outputPath & "/" & (name of thisDoc))

    (* IF YOU WANT TO SAVE MULTIPLE FILES WITH CONSECUTIVE NAMES *)
    set docNumber to docNumber + 1
    set docName to (docNumber & docExtension) as text

    set thisDoc2 to make new document with properties {name:docName} -- Removed Text Property This Time
    close thisDoc2 saving in POSIX file (outputPath & "/" & (name of thisDoc2))
end tell