无法打开文件进行写作

时间:2014-11-05 07:15:06

标签: 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 logFilePath
on error err
    display dialog err
end try

set logFile to open for access logFilePath with write permission

我收到一个对话框File file tlv-mp3u2:Users:idror:Desktop:waiting.scpt.log wasn’t open.,然后是错误error "File file tlv-mp3u2:Users:idror:Desktop:waiting.scpt.log is already open." number -49 from file "tlv-mp3u2:Users:idror:Desktop:waiting.scpt.log" to «class fsrf»

我将有问题的文件移到了垃圾箱并再次运行了脚本,结果相同

另外,我真正想要的是在/ tmp下打开文件,但如果我尝试了,我会收到“文件访问错误”(-54)

我放弃了在谷歌寻找答案......所以请帮忙

2 个答案:

答案 0 :(得分:0)

我不明白你的电话顺序。 Applescript访问文件的方式总是一样的:

  1. 打开文件并存储指向已打开文件的文件ID
  2. 如果需要,请获取文件末尾的索引(需要在末尾添加文本)
  3. 读/写您想要的内容
  4. 关闭对文件ID
  5. 的访问权限

    您的代码段看起来就像是在打开文件之前尝试关闭。如果开放工作(应该只有一次)文件仍然打开,因为你没有关闭它。也许重启可以帮助或安全地清空垃圾桶。

    要做日志,我建议:

    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
    

    问候,迈克尔/汉堡

    评论后更新:

    我在处理程序中添加了第三个参数。要删除您必须{​​{1}}的文件内容,如下所示:

    set the eof to 0

答案 1 :(得分:0)

CTRL-Click AppleScript并查看菜单Error Handlers=>Write Error to Log - 代码会准确显示其完成情况。