0

我试图在桌面上写入文件,但它会引发文件未找到错误。如果没有文件但仍然显示错误,我要求我的代码创建文件。下面是我的代码。

tell application "Finder"

    try
        set myFile to ("TestReport.txt")
        set logpath to (((path to desktop from user domain) as string)) as alias
        set logfile to myFile
        tell application "Finder" to make new file at (logpath) with properties {name:myFile}
    on error --file exist yet, so create it
        set logfile to myFile as alias
        display alert logfile
    end try
    try
        tell application "Finder" to make new file at ((path to desktop from user domain) as string) with properties {name:"TestReport.txt"}
        set logmsg to "File Rename"
        --set logmsg to (numberoflines as string) & ") " & tab & mylogin & tab & curDate & tab & thecount & tab & "Ver.1" & return
        set the logdata to (open for access file (logfile as text) with write permission)
        write logmsg to the logdata starting at eof
        close access logdata
        return true
    end try
end tell

请指教。谢谢。

4

2 回答 2

1

必须存在“别名”文件。这就是它的工作原理。因此,如果您的文件的路径不存在,当您使用“作为别名”时,它会出错。另一个问题是如果文件已经存在,Finder 在尝试创建文件时会出错。

所以你有两件事会让你的代码出错。一种是文件不存在,另一种是文件存在。很有趣,因为您的代码总是会出错。

但这是一个简单的修复。您会注意到我将所有路径都保留为字符串,并且当我想使用路径时,我会根据需要在其前面添加“文件”或“文件夹”一词。这会将字符串路径转换为文件说明符并允许使用它。它还消除了使用“作为别名”的需要,还允许我将字符串添加在一起以形成整个路径。要解决 Finder 问题,我们只需在尝试创建文件之前检查文件是否存在。尝试这个...

set myFile to "TestReport.txt"
set logpath to (path to desktop from user domain) as string
set logfile to logpath & myFile
tell application "Finder"
    if not (exists file logfile) then
        make new file at folder logpath with properties {name:myFile}
    end if
end tell
于 2013-09-17T04:45:58.193 回答
0

即使~/Desktop/file.txt不存在,这也应该有效:

set p to (system attribute "HOME") & "/Desktop/file.txt"
set fd to open for access p with write permission
write "text" & linefeed to fd as «class utf8» starting at eof
close access fd
于 2013-09-17T04:06:43.127 回答