出于某种原因,当我检查文件是否存在时,它总是返回true:
display dialog (exists (homePath & "Desktop/11-14.csv" as POSIX file as string))
无论是否在我的桌面上有一个名为csv的csv,它都会返回true。我想创建一个通过文件存在工作的if函数,但因为它总是返回true,所以它搞砸了我的if函数。我该怎么做才能解决这个问题?
答案 0 :(得分:4)
一些解释:它总是返回true的原因是文件类存在而不是驱动器上的文件。它与存在“Hello World!”一样,它总是返回true,因为字符串“Hello World!”确实存在。默认情况下,exists命令只检查给定值是否为缺失值。当它缺少值时返回false,否则返回true。但是,有些应用程序会覆盖标准的存在命令,例如System Events和Finder。因此,要对文件使用exists命令并想要检查文件是否存在,您应该将代码包装在tell system“System Events”或“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
答案 1 :(得分:0)
尝试:
set xxx to (path to desktop as text) & "11-14.csv"
tell application "System Events" to exists file xxx