【问题标题】:Applescript doesn't have write permission to fileApplescript 没有文件的写权限
【发布时间】:2021-05-28 05:50:57
【问题描述】:

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

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 路径。
  • @red_menace 我以前见过类似的关于 Finder 和 posix 路径的 cmets,但我不明白。我的理解是 posix 路径只是文件说明符,并且内置于 applescript - 与别名和文件相同。我不确定Finder与它有什么关系?您当然可以告诉 Finder 使用 posix 样式的引用。请注意,我不是在质疑答案,因为我同意 Finder 不是创建文件所必需的。只是想知道您是否可以详细说明上面的评论。
  • @Mockman :OP 尝试使用 Finder 使用 POSIX 路径创建文件 - 某些术语可以使用任何一种格式,但 Finder 使用冒号分隔的 HFS 路径。当使用带有 POSIX 路径的 Finder 时,需要使用 POSIX file 说明符来指定使用 POSIX 路径的文件(也可以使用 System Events)。有关详细信息,请参阅 AppleScript 语言指南中的 Aliases and Files 部分。
  • 但这不只是语法问题吗? OP 的代码可以通过简单地包含“posix 文件”来创建文件(撇开波浪号问题,无论如何都需要修复)。同样,我同意这个答案,但例如,如果目的是使用 shell 脚本来编写文本和做其他事情,那么 posix 文件方法就可以了。以这种方式构建它听起来有点不祥,好像这种方法充满危险并且注定要失败。即使有更好的方法,它也确实有效。
  • @Mockman AppleScript 是 OS X 之前的遗留物。在系统 7-9 中没有 UNIX 子库,因此没有 POSIX 路径。在 OS X 中,Apple 逐渐在系统事件和脚本添加等许多 API 中启用了对 POSIX 路径的支持,但 Finder 始终停留在 HFS 气泡中。

标签: applescript


【解决方案1】:

正如 cmets 中已经提到的 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

【讨论】:

  • 它工作得很好,除了它不会删除文件中之前的旧文本而是覆盖它。因此,例如,如果我有"hello world",然后只有"Dog",它不会是Dog,而是Doglo world,但我只希望它是Dog
猜你喜欢
  • 2013-04-21
  • 2022-07-16
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
相关资源
最近更新 更多