AppleScript没有对文件的写入权限 [英] Applescript doesn't have write permission to file

查看:3
本文介绍了AppleScript没有对文件的写入权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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会出现问题?

推荐答案

在注释中已经提到,查找器不知道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

这篇关于AppleScript没有对文件的写入权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆