For some reason, when I check to see if a file exists, it always returns as true:
display dialog (exists (homePath & "Desktop/11-14.csv" as POSIX file as string))
That returns as true, no matter if there is a csv named that on my Desktop or not. I want to make an if function that works through file existence, but because it's always returning as true, it's screwing up my if function. What can I do to fix this?
Some explanation: The reason why it always returns true is that the file class exists rather than the file on your drive. It's the same as saying exists "Hello World!" which always returns true because the string "Hello World!" does indeed exists. By default the exists command just checks is the given value is missing value or not. When it is missing value it returns false, otherwise it will return true. However there are applications that overwrites the standard exists command like System Events and Finder for instance. So to use the exists command on a file and want to check if the file exists you should wrap your code in an tell application "System Events" or "Finder" block like in adayzdone example code.
There are more ways to skin 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'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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With