简体   繁体   中英

Applescript renames a file, gives errors?

I have this simple code in apple script which when run is supposed to rename the file. Instead it gives me an error Can't get file "Volumes:Projects:Projects:1.pdf".

set ff to file "Volumes:Projects:Projects:1.pdf"
set ss to "Volumes:Projects:Projects:1.pdf"
set name of ff to ss

Using the following example AppleScript code , with the existence of the file set to ff at the shown path:

set ff to POSIX path of "Volumes:Projects:Projects:1.pdf"
set ss to "2.pdf"

tell application "System Events" to set name of file ff to ss

Shows the following Event in Script Editor :

tell application "System Events"
    set name of file "/Volumes/Projects/Projects/1.pdf" to "2.pdf"
end tell

Looking in Finder , 1.pdf was renamed to 2.pdf , as expected in this example.


Update: Note that vadian make a good point in 2 about the hierarchy of an HFS path , and is in part why I chose to covert it to a POSIX path . I also prefer to use System Events as it typically handle file operations faster than Finder and will work with both HFS style and POSIX style paths .

In other words, with System Events the following works:

tell application "System Events" to set name of file "Projects:Projects:1.pdf" to "2.pdf"

tell application "System Events" to set name of file "/Volumes/Projects/Projects/1.pdf" to "2.pdf"

But this too, even though malformed, works:

tell application "System Events" to set name of file "Volumes:Projects:Projects:1.pdf" to "2.pdf"

However, with Finder , only a proper HFS path works without error, it can't handle a POSIX path because it doesn't understand it as it's not in Finder 's AppleScript Dictionary.

That said, one should always make sure the information being passed is properly formed even when a malformed path would work in this example with System Events , it's not a good habit to get into!

Three major issues.

  1. To rename a file you have to tell Finder or System Events to do that.
  2. A HFS path (colon separated) starts always with a disk name, never with Volumes .
  3. To rename a file set the name property to a file name rather than to a full path .

Actually your example does nothing.

This snippet renames the file 1.pdf in folder "Projects" on disk Projects to 2.pdf

tell application "Finder"
    set name of file "Projects:Projects:1.pdf" to "2.pdf"
end tell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM