Rename a file using AppleScript

Hey folks,

Posing another question here hoping to see what answers the hive mind can help with, I am running into an issue, where I have some files that are stored inside an applet (Numbers documents), I am able to get the file to duplicate itself out to the desktop folder as expected but when trying to rename the file on the desktop I keep running into an error within Finder, as with a good number of AppleScript errors, they are rather ambiguous so wondering if someone more knowledgable has any assistance they could lend.

Code:

docName is to Document within the applet (Path to resources folder in app) then a folder containing all the workbooks
desktopFolder is a path directly to the user Desktop folder
fileToBeNamed is the variable created to store the path of the file once it is duplicated to the desktop

tell application "Finder"
	duplicate file docName to desktopFolder with replacing
	set fileToBeNamed to file fileName of desktopFolder
    set name of file fileToBeNamed to "Workbook.numbers"

Error prompts from Script Editor:
set name of file (document file “filename.numbers” of folder “Desktop” of folder “username” of folder “Users” of startup disk) to “Roster.numbers”

→ error number -1700 from document file “filename.numbers” of folder “Desktop” of folder “user” of folder “Users” of startup disk to integer

1 Like

By adding the file keyword in the last line you create a double reference, fileToBeNamed is already a file specifier.

Remove file

set name of fileToBeNamed to "Workbook.numbers"

However there is a shorter way, the duplicate operation returns the file specifier pointing to the new location. And the Finder provides a desktop constant which is by the way the root folder of the Finder

tell application "Finder"
	set fileToBeNamed to duplicate file docName to desktop with replacing
    set name of fileToBeNamed to "Workbook.numbers"
1 Like

Hi Stefan,

Thanks for the assist, I’m still learning AppleScript, as it was a file I was trying to change I thought it needed the statement there, your way worked perfectly and with the rename so I greatly appreciate that, pretty much is the icing on the cake that I have been wracking my brains over.