Search code examples
applescriptfinder

How to reference a file in Finder with AppleScript


I have a really simple question, I've googled for a pretty long time but was unable to fix it:

            tell application "Finder"
                set videoFile to "Users:username:Desktop:No Backup:Music:video.mp4"
                delete file videoFile
            end tell

This results in the following error:

Finder got an error: Can’t get file "Users:username:Desktop:No Backup:Music:video.mp4".

The same happens if I try "open file" or some other command instead of "delete".

However, the following does open the file correctly:

            tell application "QuickTime Player"
                set videoFile to "Users:username:Desktop:No Backup:Music:video.mp4"
                open videoFile
            end tell

This opens the video, so the file path must be correct.

I've also searched for a list of all the Applescript Finder commands but was unable to find anything that seemed like a proper documentation.

Edit: I also tried I tried delete (every item of folder folderPath whose name is "video.mp4"), but this results in Finder got an error: Can’t get folder "Users:username:Desktop:No Backup:Music".


Solution

  • An HFS path must start always with a disk name (replace Macintosh HD with the real name)

    tell application "Finder"
        set videoFile to "Macintosh HD:Users:username:Desktop:No Backup:Music:video.mp4"
        delete file videoFile
    end tell
    

    However there is a convenient way to use relative paths regardless of the name of the startup disk and the user name

    set desktopFolder to path to desktop as text -- returns "Macintosh HD:Users:username:Desktop:"
    tell application "Finder"
        set videoFile to desktopFolder & "No Backup:Music:video.mp4"
        delete file videoFile
    end tell
    

    In case of the desktop folder of the current user there is a still shorter way because the desktop folder is the root folder of the Finder

    tell application "Finder"
        delete file "video.mp4" of folder "No Backup:Music:"
    end tell