Applescript 没有文件的写入权限

Applescript doesn't have write permission to file

所以我正在尝试编写一个脚本,将我想要的任何文本写入我桌面上的一个新文件。

set the theText to "hello world"
set fileName to "file.txt"
set thePath to "~/Desktop/"
try
    tell application "Finder" to make file at thePath with properties {name:fileName}
end try
set myFile to open for access (thePath & fileName) with write permission
write theText to myFile
close access myFile

此代码基于 this post 上第二受欢迎的答案。当我尝试执行上面的版本时,它给了我错误:"File not open with write permission." number -61 from "~/Desktop/file.txt" to «class fsrf»。我尝试了 运行 我的代码所基于的代码,它运行得非常完美。我还用 choose file 尝试了 运行 并且也有效。为什么 Applescript 在使用预定义路径时会出现问题?

如评论中所述Finder 不知道 POSIX 路径

但即使做到了open for access不知道如何扩展波浪号,你必须指定完整路径。

创建用于写入文本的文件根本不需要 Finder。基本上这样就够了

set the theText to "hello world"
set fileName to "file.txt"
set thePath to "/Users/myself/Desktop/"
set myFile to open for access (thePath & fileName) with write permission
write theText to myFile
close access myFile

然而,这是一种不好的做法,因为写入命令可能会失败,然后文件仍处于未定义的打开状态。

最可靠且独立于用户的语法是

set the theText to "hello world"
set fileName to "file.txt"
set thePath to POSIX path of (path to desktop)
set myFile to thePath & fileName
try
    set fileDescriptor to open for access myFile with write permission
    set eof of fileDescriptor to 0
    write theText to fileDescriptor starting at eof
    close access fileDescriptor
on error
    try
        close access myFile
    end try
end try