Applescript测试文件存在

Eig*_*Bit 9 applescript if-statement file

好吧,我认为这将是一个简单的,但显然我错过了一些明显的东西.我的代码如下:

set fileTarget to ((path to desktop folder) & "file$") as string

if file fileTarget exists then
    display dialog "it exists"
else
    display dialog "it does not exist"
end if
Run Code Online (Sandbox Code Playgroud)

容易吗?不幸的是,当我运行脚本时,它返回错误

Can’t get file "OS X:Users:user:Desktop:files$".
Run Code Online (Sandbox Code Playgroud)

文件是否存在无关紧要,这与我得到的错误相同.我已经尝试了十几种不同的东西,但它仍然让我感到困惑.

Phi*_*gan 19

我使用这个子程序来查看文件是否存在:

on FileExists(theFile) -- (String) as Boolean
    tell application "System Events"
        if exists file theFile then
            return true
        else
            return false
        end if
    end tell
end FileExists
Run Code Online (Sandbox Code Playgroud)

加盐调味.


reg*_*633 6

这很容易,除了"exists"是Finder或System Events命令.这不是一个直接的AppleScript命令.因此,您必须将其包装在tell应用程序代码块中.仅供参考:这是另一种不需要申请的方式.它的工作原理是因为当您强制通向"别名"的路径时,它必须存在,否则您会收到错误.所以你可以做到以下几点.

set fileTarget to (path to desktop folder as text) & "file$"

try
    fileTarget as alias
    display dialog "it exists"
on error
    display dialog "it does not exist"
end try
Run Code Online (Sandbox Code Playgroud)

注意:您的代码中有错误.你正在使用&运算符来添加字符串,但是你做错了,尽管运气得到了正确的答案.使用&运算符时,运算符两侧的每个对象都必须是一个字符串."桌面文件夹的路径"不是字符串,所以我们首先必须使它成为一个字符串,然后将字符串"file $"添加到它.所以这样做......

set fileTarget to (path to desktop folder as text) & "file$"
Run Code Online (Sandbox Code Playgroud)