Script Error: Can’t get file

Hi,

I have the following AppleScript that checks whether the file test.csv exists on the desktop. When I run the code, the following message appears: Script Error: Can’t get file ‘Macintosh HD:Users:adam:Desktop:test.csv’.

set fileTarget to (path to desktop as text) & "test.csv"

if file fileTarget exists then

display dialog "it exists"

else

display dialog "it does not exist"

end if

Can you please advise where the error might be? Yes, the file really exists on the desktop. I have checked it three times."

“Path to desktop folder”

path to desktop is valid. It’s mandatory to ask the Finder or System Events for existence, AppleScript itself has no idea.

Actually AppleScript does.

Try
    Alias ((path to desktop as text) & “test.csv”)
    display dialog “it exists”
error
    display dialog “it does not exist”
End try

try this:

set fileTarget to (path to desktop as text) & "test.csv"
tell application "Finder"
	if file fileTarget exists then
		
		display dialog "it exists"
		
	else
		
		display dialog "it does not exist"
		
	end if
end tell

path to is from scripting editions, so it does not need to be in a finder tell block

Display dialog is also in scripting additions, but works within the finder tell.

If you prefer you can use

tell application "System Events"

instead of finder.

Typo alert: Several of your quote marks are curly.

Thank you very much.

Brute force doesn’t count :wink:

As an aside specific to desktop, it’s also a Finder keyword, so the script could be written without the path to command:

set fileName to "test.csv"
tell application "Finder"
	if (file fileName of desktop exists) then
		display dialog "it exists"
	else
		display dialog "it does not exist"
	end if
end tell

In fact the desktop’s the default location in the Finder, so it doesn’t even have to be specified:

set fileName to "test.csv"
tell application "Finder"
	if (file fileName exists) then
		display dialog "it exists"
	else
		display dialog "it does not exist"
	end if
end tell

System Events has an equivalent in desktop folder, but this does have to be included in a specifier:

set fileName to "test.csv"
tell application "System Events"
	if (file fileName of desktop folder exists) then
		display dialog "it exists"
	else
		display dialog "it does not exist"
	end if
end tell
2 Likes