Applescript testing for file existence

試著忘記壹切 提交于 2019-12-30 04:35:20

问题


OK, I thought this would be a simple one, but apparently I'm missing something obvious. My code is as follows:

set fileTarget to ((path to desktop folder) & "file$") as string

if file fileTarget exists then
    display dialog "it exists"
else
    display dialog "it does not exist"
end if

Easy right? Unfortunately, when I run the script it returns the error

Can’t get file "OS X:Users:user:Desktop:files$".

It doesn't matter if the file exists or not, this is the same error I get. I've tried a dozen different things but it still stumps me.


回答1:


I use this subroutine to see if a file exists or not:

on FileExists(theFile) -- (String) as Boolean
    tell application "System Events"
        if exists file theFile then
            return true
        else
            return false
        end if
    end tell
end FileExists

Add salt to taste.




回答2:


It is easy except "exists" is a Finder or System Events command. It's not a straight applescript command. As such you must wrap it in a tell application code block. FYI: here's another way that doesn't require an application. It works because when you coerce a path to an "alias" it must exist otherwise you get an error. So you could do the following.

set fileTarget to (path to desktop folder as text) & "file$"

try
    fileTarget as alias
    display dialog "it exists"
on error
    display dialog "it does not exist"
end try

NOTE: you have an error in your code. You're using the & operator to add strings but you're doing it wrong although you're getting the right answer by luck. When you use the & operator, each object on either side of the operator must be a string. "path to desktop folder" is not a string so we first must make that a string and then add the string "file$" to it. So do it like this...

set fileTarget to (path to desktop folder as text) & "file$"



回答3:


to avoid original error Can’t get file "OS X:Users:user:Desktop:files$". simply add to script tell block tell application "Finder" set fileTarget to ((path to desktop folder) & "file$") as string

if file fileTarget exists then display dialog "it exists" else display dialog "it does not exist" end if end tell



来源:https://stackoverflow.com/questions/3469389/applescript-testing-for-file-existence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!