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

use*_*712 5 applescript

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

display dialog (exists (homePath & "Desktop/11-14.csv" as POSIX file as string))
Run Code Online (Sandbox Code Playgroud)

无论是否在我的桌面上有一个名为csv的csv,它都会返回true.我想创建一个通过文件存在工作的if函数,但因为它总是返回true,所以它搞砸了我的if函数.我该怎么做才能解决这个问题?

dj *_*zie 4

一些解释:它总是返回 true 的原因是文件类存在而不是驱动器上的文件。这与说存在“Hello World!”是一样的。它总是返回 true,因为字符串“Hello World!” 确实存在。默认情况下,exists 命令仅检查给定值是否缺少值。当缺少值时返回 false,否则返回 true。然而,有些应用程序会覆盖标准的现有命令,例如系统事件和查找器。因此,要在文件上使用exists命令并想要检查文件是否存在,您应该将代码包装在告诉应用程序“系统事件”或“Finder”块中,如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
Run Code Online (Sandbox Code Playgroud)