AppleScript——检查文件是否存在不起作用

AppleScript——检查文件是否存在不起作用,applescript,Applescript,出于某种原因,当我检查某个文件是否存在时,它总是返回true: display dialog (exists (homePath & "Desktop/11-14.csv" as POSIX file as string)) 无论在我的桌面上是否有一个名为它的csv,它都返回为true。我想创建一个通过文件存在来工作的if函数,但是因为它总是返回true,所以它把我的if函数搞砸了。我能做些什么来解决这个问题?试试: set xxx to (path to desktop as tex

出于某种原因,当我检查某个文件是否存在时,它总是返回true:

display dialog (exists (homePath & "Desktop/11-14.csv" as POSIX file as string))
无论在我的桌面上是否有一个名为它的csv,它都返回为true。我想创建一个通过文件存在来工作的if函数,但是因为它总是返回true,所以它把我的if函数搞砸了。我能做些什么来解决这个问题?

试试:

set xxx to (path to desktop as text) & "11-14.csv"
tell application "System Events" to exists file xxx

一些解释:它总是返回true的原因是file类存在,而不是驱动器上的文件。这与说exists“helloworld!”相同,它总是返回true,因为字符串“helloworld!”确实存在。默认情况下,exists命令只检查给定值是否缺少值。当它缺少值时,将返回false,否则将返回true。但是,有些应用程序会覆盖标准的exists命令,例如System Events和Finder。因此,要在文件上使用exists命令并检查文件是否存在,您应该将代码包装在一个告诉应用程序“系统事件”或“查找器”块中,如adayzdone示例代码中所示

有更多的方法可以剥这只猫的皮

set theFile to "/Users/wrong user name/Desktop"

--using system events 
tell application "System Events" to set fileExists to exists disk item (my POSIX file theFile as string)

--using finder
tell application "Finder" to set fileExists to exists my POSIX file theFile

--using alias coercion with try catch
try
    POSIX file theFile as alias
    set fileExists to true
on error
    set fileExists to false
end try

--using a do shell script
set fileExists to (do shell script "[ -e " & quoted form of theFile & " ] && echo true || echo false") as boolean

--do the actual existence check yourself
--it's a bit cumbersome but gives you an idea how an file check actually works
set AppleScript's text item delimiters to "/"
set pathComponents to text items 2 thru -1 of theFile
set AppleScript's text item delimiters to ""
set currentPath to "/"
set fileExists to true
repeat with component in pathComponents
    if component is not in every paragraph of (do shell script "ls " & quoted form of currentPath) then
        set fileExists to false
        exit repeat
    end if
    set currentPath to currentPath & component & "/"
end repeat
return fileExists