gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:15:29 26 4
gpt4 key购买 nike

出于某种原因,当我检查文件是否存在时,它总是返回 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。因此,要对文件使用存在命令并想要检查文件是否存在,您应该将代码包装在告诉应用程序“系统事件”或“查找器” block 中,就像在 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

关于AppleScript——检查文件是否存在不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com