文件存在不起作用

时间:2014-10-12 15:15:51

标签: file applescript exists

我试图检测文件是否存在。但是,脚本会停止并出错,而不是转到“else”语句。

知道如何使这项工作吗?

tell application "Finder" 

    if exists file h then 

        display dialog "file exists"

    else

        display dialog "file doesnt exist"

    end if

end tell

干杯

2 个答案:

答案 0 :(得分:1)

这里有一个小例子:

set h to (choose file with prompt "Pick a file…") as string

tell application "Finder"

    if exists file h then

        display dialog "file " & return & quoted form of h & return & " exists"

    else

        display dialog "file " & return & quoted form of h & return & " missing!"

    end if

end tell

或者不使用as string使其更简单:

set h to (choose file with prompt "Pick a file…")

tell application "Finder"

    if exists h then

        display dialog "file " & return & quoted form of (h as text) & return & " exists"

    else

        display dialog "file " & return & quoted form of (h as text) & return & " missing!"

    end if

end tell

答案 1 :(得分:0)

使用@PhilipRegan's subroutine from this answer,以下内容似乎按预期工作:

set h to "/mach_kernel"
if FileExists(h) then
    display dialog (h & " exists!")
else
    display dialog (h & " does not exist")
end if

set h to "/foo"
if FileExists(h) then
    display dialog (" exists!")
else
    display dialog (h & " does not exist")
end if

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

enter image description here

enter image description here