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