get name of file from file path using AppleScript
I am trying to get the name of file using AppleScript with the following code:
tell application "Finder"
set filename to name of "/Users/mainuser/Desktop/Test/shot.png" // should return shot.png
display dialog filename
end tell
I am getting an error saying:
error "Can’t get name of \"/Users/mainuser/Desktop/Test/shot.png\"." number -1728 from name of "/Users/mainuser/Desktop/Test/shot.png"
What I am doing wrong?
Solution 1:
Using the file pathname from your question, here is the AppleScript code that should work.
tell application "Finder"
set fileName to name of (POSIX file "/Users/mainuser/Desktop/Test/shot.png" as alias)
display dialog fileName
end tell
A more direct way of the above scenario is:
Syntax:
set fileName to name of (info for "/path/to/file")
display dialog fileName
Example (using the pathname in your question):
set fileName to name of (info for "/Users/mainuser/Desktop/Test/shot.png")
display dialog fileName
The shortest way to display the name of a file from its pathname in a dialog box is:
Syntax:
display dialog name of (info for "/path/to/file")
Example (using the pathname in your question):
display dialog name of (info for "/Users/mainuser/Desktop/Test/shot.png")