AppleScript Tutorial: File and Folder Path Name
19 February 2009
If you ever started to work with file and folder pathname you may have found it more than a bit confusing or even irritating.
Here are a few tips and tricks to getting your code working quicker.
What Format Should I Use?
You may have seen two different types of paths being used to access a fileExample 1 - "/Users/computername/Desktop/filename.txt"
Example 2 - “Macintosh HD:Users:computername:Desktop:filename.txt”
If my computer name is “James” then Example 2 would look like:
“Macintosh HD:Users:James:Desktop:filename.txt”
Which one is correct?
The second example (Example 2) is correct for opening files. Try the following code.
Example AppleScript Code:
set FileName to "Macintosh HD:Users:James:Desktop:filename.txt"
tell application "Finder"
--open the file in the default application
open file FileName
end tell
Converting file path Formats
You can easily convert pathname format using the POSIX command as follows: Example AppleScript Code:set FileName to "/Users/James/Desktop/filename.txt"
set FileName to POSIX file FileName
tell application "Finder"
--open the file in the default application
open file FileName
end tell
Simple Access to Desktop Files
If you don’t wish to write out the full pathname to the desktop each time, you can use the following code. Example AppleScript Code:set FileName to (path to desktop as text) & "filename.txt"
tell application "Finder"
--open the file in the default application
open file FileName
end tell
Easy Access to files in your Documents Folder
Say you wish to access a file called “Budget.xls” within the folder “Excel Docs” within your Documents Folder, you can easily access this file with the following code.
set FileName to (path to documents folder as text) & "Excel Docs:Budget.xls"
tell application "Finder"
--open the file in the default application
open file FileName
end tell
Well that is a pretty quick overview and we hope that this will help you avoid the traps so many of us fall into when dealing with files and paths.
Reference Documents
To review the complete AppleScript Guide as well as other AppleScript Guides for MS Word, Excel, PowerPoint or Adobe Photoshop please review the “Reference Documents” page on this website.AppleScript Reference Documents
Best of luck with your AppleScripting adventures.
Regards,
Thompson-Solutions