AppleScript - checking for file does not work

For some reason, when I check if a file exists, it always returns as true:

display dialog (exists (homePath & "Desktop/11-14.csv" as POSIX file as string)) 

This returns true, regardless of whether csv exists on my desktop or not. I want to create an if function that works through the existence of a file, but since it always returns as true, it twists my if function. What can I do to fix this?

+4
source share
2 answers

Some explanation. The reason it always returns true is because the file class exists and not the file on your disk. This is the same as saying "Hello World!" which always returns true because the string is "Hello World!" really exists. By default, the command just tested exists - this value is missing or not. When this value is absent, it returns false, otherwise it will return true. However, there are applications that overwrite a standard existing command, such as System Events and Finder. Thus, to use the exists command in a file and want to check if the file exists, you must wrap your code in the System Events or Crawler application, as in the adayzdone code example.

There are many ways to throw this cat.

 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 a bit cumbersome but gives you an idea how an file check actually works set AppleScript text item delimiters to "/" set pathComponents to text items 2 thru -1 of theFile set AppleScript 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 
+3
source

Try:

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

Source: https://habr.com/ru/post/1446066/


All Articles