Applescript - 在桌面上写入文件

时间:2013-09-17 03:06:51

标签: applescript

我试图在桌面上写文件,但它会抛出找不到文件的错误。我问我的代码创建文件,如果没有文件,但仍然显示错误。以下是我的代码。

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

请指教。感谢。

2 个答案:

答案 0 :(得分:1)

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

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

但这是一个简单的修复。您会注意到我将所有路径保留为字符串,当我想使用路径时,我会在其前面放置“file”或“folder”一词。这会将字符串路径转换为文件说明符并允许使用它。它还消除了使用“as alias”的需要,并且还允许我将字符串添加到一起以形成整个路径。要解决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

答案 1 :(得分: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