Applescript 无法打开文件进行写入
我正在尝试创建一个日志文件,如下所示:Applescript 无法打开文件进行写入,applescript,Applescript,我正在尝试创建一个日志文件,如下所示: set logFilePath to (path to desktop folder as string) & "waiting.scpt.log" -- "/tmp/waiting.scpt.log" as text -- set logFilePath to (path to "temp" from user domain as text) & "waiting.scpt.log" try close access file
set logFilePath to (path to desktop folder as string) & "waiting.scpt.log" -- "/tmp/waiting.scpt.log" as text
-- set logFilePath to (path to "temp" from user domain as text) & "waiting.scpt.log"
try
close access file logFilePath
on error err
display dialog err
end try
set logFile to open for access logFilePath with write permission
我看到一个对话框,上面说文件tlv-mp3u2:Users:idor:Desktop:waiting.scpt.log没有打开。然后,错误文件tlv-mp3u2:Users:idor:Desktop:waiting.scpt.log已打开。文件tlv-mp3u2中的编号-49:Users:idor:Desktop:waiting.scpt.log到«class fsrf»
我将有问题的文件移到垃圾箱,然后再次运行脚本,结果相同
另外,我真正想要的是在/tmp下打开文件,但是如果我尝试打开,我会得到文件访问错误-54
我已经放弃在谷歌上寻找答案。。。因此,请帮助我,我不明白你打电话的顺序。Applescript访问文件的方式始终相同: 打开文件并存储指向打开文件的文件id 如果需要,获取在文件末尾追加文本所需的文件末尾的索引 读/写你想要的内容 关闭对文件id的访问 您的代码段看起来像是在打开文件之前尝试关闭的。如果打开有效,应该只打开一次文件,因为您没有关闭它。也许重新启动有帮助,或者安全地清空垃圾 要执行日志,我建议:
set logFilePath to (path to desktop folder as string) & "waiting.scpt.log"
doLog(logFilePath, "A new line to log!")
on doLog(pathToLogFile, logText)
try
-- open the file at logFilePath and store the file id
set logFile to open for access pathToLogFile with write permission
-- write the given text to the file, starting at the end of file to append
write logText & return to logFile starting at (get eof logFile) + 1
-- close the file asap
close access logFile
on error
-- if something went wrong, finally try to close the file!
try
close access logFile
end try
end try
end doLog
你好,迈克尔/汉堡
评论后更新:
我向处理程序添加了第三个参数。要删除文件内容,必须按如下方式将eof设置为0:
doLog(logFilePath, "A new line to log!", true)
on doLog(pathToLogFile, logText, appendLog)
try
-- open the file at logFilePath and store the file id
set logFile to open for access pathToLogFile with write permission
-- set the eof to 0, if appending is not wished
if not appendLog then
set eof logFile to 0
end if
-- write the given text to the file, starting at the end of file to append
write logText & return to logFile starting at (get eof logFile) + 1
-- close the file asap
close access logFile
on error
-- if something went wrong, finally try to close the file!
try
close access logFile
end try
end try
end doLog
CTRL单击一个AppleScript并签出菜单Error Handlers=>Write Error to Log(错误处理程序)=>Write Error to Log(将错误写入日志)-代码将准确显示它是如何完成的。CTRL单击一个AppleScript并签出菜单Error Handlers=>Write Error to Log(错误处理程序写入日志)-代码将准确显示它是如何完成的。@Zero:这是最好的简明答案,并生成完整的解决方案。如果您作为答案发布,我将接受删除文件内容,您必须将其eof设置为0。我更新了我的答案!最后,我将路径声明为全局变量,然后将eof设置为0