Can Applescript be used to tell whether or not a directory (path) exists?

大城市里の小女人 提交于 2020-01-15 13:04:54

问题


I've got some Applescript code that switches to a specified directory by KEYSTROKEing the path into the "Go To" dialog.

Regretfully, this dialog does NOT raise an error if the requested directory does not exist?! It just goes as far as it can along the path and then DUMPS THE NONEXISTENT PATH FRAGMENT into the default text field of whatever window is under it!

Example: given "~/Music/nonexistent" it would switch to the Music folder in the user's home folder then 'type' "nonexistent" into the underlaying window's default text field if it has one.

Consequently, I need to know how to find out if a given path already exists or not from Applescript.


回答1:


In AppleScript you can simply check if a path exists by coercing the path to an alias specifier. If the path does not exist an error is thrown

Further you have to expand the tilde programmatically. The handler returns a boolean value.

on checkPathExists(thePath)
    if thePath starts with "~" then set thePath to POSIX path of (path to home folder) & text 3 thru -1 of (get thePath)
    try
        POSIX file thePath as alias
        return true
    on error
        return false
    end try
end checkPathExists

set pathisValid to checkPathExists("~/Music/nonexistent")

Alternatively use System Events, but sending an Apple Event is a bit more expensive:

set thePath to "~/Music/nonexistent"
tell application "System Events" to set pathisValid to exists disk item thePath



回答2:


What about something like this?

set theFolder to "path:to:the:Folder:" --your folder/path


if FolderExists(theFolder)=true then -- HERE YOU DON'T have to put exists again, it's already check in the handler FolderExists(theFolder)

      display dialog "Exists " & theFolder & " !"

else

      display dialog "Missing " & theFolder & " !"

end if

--handler for checking if exists theFolder/thePath

    on FolderExists(theFolder) -- (String) as Boolean
        tell application "System Events"
            if exists folder theFolder then
                return true
            else
                return false
            end if
        end tell
    end FolderExists


来源:https://stackoverflow.com/questions/42058669/can-applescript-be-used-to-tell-whether-or-not-a-directory-path-exists

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