AppleScript: copy a file to a new location, changing its name

I want to copy a selected file to a new location and change its name, both location and name adjustable by the user. It would seem natural to me (a neophyte) to use the Duplicate and Choose File Name commands to do this, so this is the module I came up with:
tell application "Finder"
          set myFile to the selection
          set textsAlias to alias "Campidoglio:Users:jeffreyjdean:Dropbox:Tinctoris:Editing Software:TextToJS:texts:"
          set fileForConversion to choose file name default name "shortname.txt" default location textsAlias
          try
  duplicate document file myFile to fileForConversion with replacing
          on error
                    display dialog "Error: Unable to save file."
          end try
end tell
This doesn't work. The error dialog comes up and this is the result report:
tell application "Finder"
  get selection
  --> {document file "12 De inventione et usu musice.txt" of folder "Edited texts" of folder "Desktop" of folder "jeffreyjdean" of folder "Users" of startup disk}
  choose file name default name "shortname.txt" default location alias "Campidoglio:Users:jeffreyjdean:Dropbox:Tinctoris:Editing Software:TextToJS:texts:"
  --> file "Campidoglio:Users:jeffreyjdean:Dropbox:Tinctoris:Editing Software:TextToJS:texts:shortname.txt"
  -- 'core'\'clon'{ 'insh':'furl'("file://localhost/Users/jeffreyjdean/Dropbox/Tinctoris/Editing%20 Software/TextToJS/texts/shortname.txt"), 'alrp':'true'("true"), '----':'obj '{ 'form':'indx', 'want':'docf', 'seld':[ 'obj '{ 'form':'name', 'want':'docf', 'seld':'utxt'("12 De inventione et usu musice.txt"), 'from':'obj '{ 'form':'name', 'want':'cfol', 'seld':'utxt'("Edited texts"), 'from':'obj '{ 'form':'name', 'want':'cfol', 'seld':'utxt'("Desktop"), 'from':'obj '{ 'form':'name', 'want':'cfol', 's…
  --> error number -1700 from {document file "12 De inventione et usu musice.txt" of folder "Edited texts" of folder "Desktop" of folder "jeffreyjdean" of folder "Users" of startup disk} to integer
  display dialog "Error: Unable to save file."
  --> {button returned:"OK"}
end tell
Result:
{button returned:"OK"}
Why is it telling me it can't duplicate a file to an integer? According to the AS Language Guide, the result of Choose File Name is "The selected location, as a file." How does this become an integer in my script?
That may be a side show. What I really want to work out is how to achieve the aim stated at the beginning: take a selected file (that part is working OK) and duplicate it to an arbitrary location with an arbitrary new name, decided by the user. What's the best way to go about this?
TIA,
Jeff
Message was edited by: Jeffrey Dean

I think you're misinterpreting the error message.
It's not complaining about your 'Choose File Name', per se.
There are two problems with your script.
First, you:
          set myFile to the selection
As far as the Finder is concerned, 'selection' is a list. It's always a list, even if only one item is selected - heck, it's still a list if no files are selected... just an empty list.
So that's the first thing the script is complaining about - you are using a list that you're trying to coerce to a file. Can't happen.
You have a couple of options here, depending on what you want to do.
You can tell the Finder to duplicate a list - it will simply duplicate all the files in the list. It has no problem with that, although you're going to run into problems when you try to set the file name(s). This highlights one of the design flaws with your script - how do you know the user only has one thing selected? At the very least you should check how many items are selected and react accordingly.
The other option is to iterate through the list, duplicating each file in turn. Again, it's not clear what you want/expect the outcome to be here - since you include 'with replacing', you'd likely end up with one file (the last one in the list) as being the named file and all other duplicates lost.
The third option is to expect there to be one item selected, and just act upon the first one - thereby ignoring multiple selections, although it's undefined as to which item is 'first' in the list.
Your call.
Once you get over the issue of identifying what you want to duplicate, the second issue with your script is how you're calling duplicate. You cannot duplicate one file to another file name. The duplicate command expects (demands?) a directory as the 'to' parameter, not a file name.
In other words, you can duplicate a file to a new directory. You cannot duplicate it to a new file name - at least not in one step. In order to do that you need to duplicate the file, then change its name (or use a shell script to do it 'under the hood').
This is complicated by the fact that it's the rename that requires you to check for duplicates, which you have to do manually.
So given the above, and assuming you expect/want one item to be selected, your script should look more like:
tell application "Finder"
          set myFile to item 1 of (get selection) -- ignore multiple selections
          set textsAlias to alias "Campidoglio:Users:jeffreyjdean:Dropbox:Tinctoris:Editing Software:TextToJS:texts:"
          set fileForConversion to choose file name default name "shortname.txt" default location textsAlias
          set fDir to do shell script "/usr/bin/dirname " & POSIX path of fileForConversion
          set fName to do shell script "/usr/bin/basename " & POSIX path of fileForConversion
          try
                    set newFile to duplicate myFile to POSIX file fDir with replacing
                    if (exists file fName of folder fDir) then
  delete file fName of folder fDir
                    end if
                    set name of newFile to fName
          on error
                    display dialog "Error: Unable to save file."
          end try
end tell
Incidentally, this is something that could be much more easily done with a shell command, since the shell isn't as sensitive about file paths and data types.

Similar Messages

  • A script for copying smilar files to a new location

    Hi,
    i newbies to scripting. My challenge is that I want a script to only copy files with names "similar" and not "exactly the same" as the filenames in the text file.
    For example some files have 10 letters file name like "ABC01FGH01.tif".  I have to copy file where starting letter "ABC" and middle letter "FGH" of file name are fixed, but other letters are changed.
    The script sees a file name like "ABC**FGH**.tif", it should search the source location and copy the files having filenames with at least this characters e.g. "ABC02FGH02.tif", "ABC03FGH04.tif" should be copied since it has
    contains "ABC**FGH**.tif".
    Please help.

    Learn how to use wildcards in file names.  '*' is for any number of characters and'?' is for one character.
    COPY ABC??DE???.?x? c:\target
    Start by using DIR
    DIR ABC??DEF???JK.?x?
    ¯\_(ツ)_/¯

  • Wait for download to complete, then copy the file to a new location

    I am downloading some files with PowerShell using webclient.downloadfileasync. 
    Im using "Start-sleep -s 10" to prevent the files to be copied before it is completed, but sometimes the download takes longer than 10 Seconds or the url is not accessible. Is there some way to check when the file is completed?
    Or maybe another solution is to check the url before it even starts downloading.
    try
    foreach ($urls in $ip)
    $url = $http + $ip
    $path = $local + $nr + $jpg
    $client = New-Object System.Net.WebClient
    $client.DownloadFileAsync($url, $path)
    finally
    $client.dispose()
    Start-sleep -s 10
    Copy-Item C:\data\*.jpg C:\data\images
    $cn.Close()

    Hi,
    Try using the DownloadFile method instead of DownloadFileAsync:
    http://msdn.microsoft.com/en-us/library/ms144194%28v=vs.110%29.aspx
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • A script for copying certain files to a new location

    I have a folder with over 50,000 images in it. I need about 15,000 of them copied to another folder.
    Is there a script (that I can paste the list of the ones I need copied) to perform this action?
    Thanks in advance.

    perhof,
    After much googling, I was fortunate enough to find your beautiful script!
    I added a couple of things like subfolder recusion ( by tweaking scripts I found) .
    Would you be kind enough to look this over and see if it's ok or needs fixing?
    Thanks for any help,
    ec
    [code]
    ' Read a list of images from text file
    ' and copy those images from SourceFolder\SubFolders to TargetFolder
    ' Should files be overwriten if they already exist? TRUE or FALSE.
    Const blnOverwrite = TRUE
    Dim objFSO, objShell, WSHshell, objFolder, objFolderItem, strExt, strSubFolder
    Dim objFileList, strFileToCopy, strSourceFilePath, strTargetFilePath
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objShell = CreateObject("Shell.Application")
    Set WSHshell = CreateObject("WScript.Shell")
    Const ForReading = 1
    ' Make the script useable on anyone's desktop without typing in the path
    DeskTop = WSHShell.SpecialFolders("Desktop")
    strFileList = DeskTop & "\" & "images.txt"
    ' File Extension type
    strExt = InputBox("Please enter the File type" _
    & vbcrlf & "For Example: jpg or tif")
    If strExt="" Then
       WScript.Echo "Invalid Input, Script Canceled"
    Wscript.Quit
    End if
    ' Get the source path for the copy operation.
    Dim strSourceFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select source folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strSourceFolder = objFolderItem.Path
    ' Get the target path for the copy operation.
    Dim strTargetFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select target folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strTargetFolder = objFolderItem.Path
    Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False)
    On Error Resume Next
    Do Until objFileList.AtEndOfStream
        ' Read next line from file list and build filepaths
        strFileToCopy = objFileList.Readline & "." & strExt
        ' Check for files in SubFolders
        For Each strSubFolder in EnumFolder(strSourceFolder)
          For Each strFileToCopy in oFSO.GetFolder(strSubFolder).Files
        strSourceFilePath = objFSO.BuildPath(strSubFolder, strFileToCopy)
        strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
        ' Copy file to specified target folder.
        Err.Clear
        objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite
        If Err.Number = 0 Then
            ' File copied successfully
            iSuccess = iSuccess + 1
            If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
                ' Running cscript, output text to screen
                Wscript.Echo strFileToCopy & " copied successfully"
            End If
        Else
            ' Error copying file
            iFailure = iFailure + 1
            TextOut "Error " & Err.Number & _
            " (" & Err.Description & ")trying to copy " & strFileToCopy
        End If
       Next
    Next
    Loop
    strResults = strResults + 0 '& vbCrLf
    strResults = strResults & iSuccess & " files copied successfully." & vbCrLf
    strResults = strResults & iFailure & " files generated errors" & vbCrLf
    Wscript.Echo strResults
    Sub TextOut(strText)
        If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
            ' Running cscript, use direct output
            Wscript.Echo strText
        Else
            strResults = strResults & strText & vbCrLf
        End If
    End Sub
    Function EnumFolder(ByRef vFolder)
    Dim oFSO, oFolder, sFldr, oFldr
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    If Not IsArray(vFolder) Then
    If Not oFSO.FolderExists(vFolder) Then Exit Function
    sFldr = vFolder
    ReDim vFolder(0)
    vFolder(0) = oFSO.GetFolder(sFldr).Path
    Else sFldr = vFolder(UBound(vFolder))
    End If
    Set oFolder = oFSO.GetFolder(sFldr)
    For Each oFldr in oFolder.Subfolders
    ReDim Preserve vFolder(UBound(vFolder) + 1)
    vFolder(UBound(vFolder)) = oFldr.Path
    EnumFolder vFolder
    Next
    EnumFolder = vFolder
    End Function
    [/code]

  • I can't import photos from a card, file or anything.  I get "could not copy a file to the requested location"..  This has never happened before.

    I can't import photos from a card, file or anything.  I get "could not copy a file to the requested location".  I have never had this happen before.  I use a MacBook Pro

    I also have the exact same issue.  New IMac, installed LR, imported approximately 900 photos no problem, across the network from a Windows PC.   The import stopped when the network connection was lost.   Now I cannot import for the same reason "could not copy a file to the requested location".  I have plenty of disk space and i have permission to the needed folders.   I cannot even import from a folder already on the IMac.   

  • From Forms 5.0 I want to copy a file/folder from one location to another.

    Hi,
    I have a question and I really appreciate your help.
    My Question is
    I would like to copy a file/folder from one location to another.
    (For ex: From my Hard disk to a Network folder).
    I want to do this from Oracle Forms 5.0 and my operating system is Windows 2000/NT Workstation.
    At present my users are doing this by using drag and drop windows functionality,
    But now they want to do this by using a GUI screen.
    I would greatly appreciate if somebody can answer my question.
    Thank you very much and have a nice day.
    Thanks & Regards
    Sanjeev.

    Hi Shay,
    Am able to copy the files/folders by doing the follwing.
    Declare
    My_Command Varchar2(1000);
    Begin
    MY_COMMAND := 'XCOPY /E ' ||:FROM_LOC ||' '|| :TO_LOC ;
    HOST(MY_COMMAND);
    End;
    But my problem is am not able to trap the errors.
    Do you have any idea?
    Thanks

  • In PC I have changed the default app location from default to other and copied the previous content to new location and changed the Default location in preference. Now in iTunes, my previous apps are not visible. Is there any solution to this?

    In PC I have changed the default app location from (c:/users/username/My Music/iTunes) to other (d:iTunes)  and copied the previous content to new location and changed the Default location in Edit preference. Now in iTunes, my previous apps are not visible. Is there any solution to this?

    wjosten - thanks very much for the detailed instructions. I'll try this as soon as I get my replacement and it looks like you'll probably end up getting the green tick

  • In pages,how do I copy an image to a new location by click & drag?

    in pages,how do I copy an image to a new location by click & drag?

    To MOVE an image to a new location, Click and Drag the image.
    To move a COPY of the image to a new location, leaving the original in place, pres and hold the Option key as you Click and Drag the image.
    Regards,
    Barry

  • "Could not copy a file to the requested location." error

    Hi - I'm running Adobe Lightroom 1.4.1 (latest) on my iMac which is running Leopard's latest version. Suddenly I'm getting an error when importing to Lightroom. I have used different CF cards, so I'm sure it's Lightroom. Either one or two photos import (out of a large amount - this happens whether in RAW or JPG) and then it quits with a pop-up, which at the very top says "Import Results", and under there it says, "Some import operations were not performed." In the space below there's a header that says, "Could not copy a file to the requested location. (92)" (Not always 92, sometimes 200 or something else), and there is a triangle to expand and all the photo file names are listed below.
    Everything was running fine until yesterday, nothing changed. I have screen shots of the error if needed. Help??? Please! I have so many photos to import!
    Thanks for any help,
    Aviva

    Same problem here only with images burned to disks today, it is fine with images burned to disks 3 days ago. This is happening on two computers one is running XP with Lightroom 1.4 the other is running Vista with Lightroom 1.3. I can import one image at a time but no batches off DVD or CD disks, I have not tried directly from my CF cards. We have found a work around; download all images to temp folder on desktop then import into Lightroom after imported delete files in temp folder it works but takes a lot more time and space on hard drive.

  • HT4889 when using migration does it copy the files to the new computer or transfer (leaving the files only on the new computer)?

    when using migration does it copy the files to the new computer or transfer them (leaving the files only on the new computer)?

    It leaves them on the old computer. Nothing will be changed on it.

  • Moving datafiles to a new location: change not flushed

    Hi all,
    I am using Oracle 10g release 10.2.0.1.0 patched 10.2.0.3.0
    I need to move all datafiles of the DB from a current location to a new one. Here are the steps I follow (I use SPFILE):
    1-Shutdown the DB
    2-Move all .DBF .LOG .CTL files to the new location
    3-startup mount
    4-alter database rename file 'old location' to 'new location' ; ... for all .DBF and .LOG files
    5-alter system set control_file=<list of CTL files in new location>
    6-alter system set core_dump_dest=<new empty location for cdump>
    7-alter system set user_dump_dest=<new empty location for udump>
    8-alter system set background_dump_dest=<new empty location for bdump>
    9-alter database open
    From this point, if I use select * from v$logfile or select name from v$datafile or show parameter, I see that the DB is using all files in the new location. That's correct.
    My problem is: if now, I issue a shutdown followed by a startup, the DB will then show the old location for files as if my updates (steps 1 to 9) were not flushed/commited.
    Is there a kind of commit to have my changes taken into account ? How may I resolve my problem ?
    Thanks for any help.

    This does not work:
    1-Shutdown the DB
    2-startup mount
    3-alter database rename file 'old location' to 'new location' ; ... for all .DBF and .LOG files
    4-alter system set control_file=<list of CTL files in new location>
    5-alter system set core_dump_dest=<new empty location for cdump>
    6-alter system set user_dump_dest=<new empty location for udump>
    7-alter system set background_dump_dest=<new empty location for bdump>
    (So changes are now in the old location)
    8-shutdown
    8-copy all .DBF .LOG .CTL files to the new location
    9-startup
    ... because when the alter database statement is issued, oracle does not find the file in 'new location'. So the correct sequence with the spfile is:
    1-Shutdown the DB
    2-copy all .DBF .LOG to the new location. Do not copy the .CTL files at this step.
    3-startup mount
    3-alter database rename file 'old location' to 'new location' ; ... for all .DBF and .LOG files
    (Oracle finds them in the new location)
    4-alter system set control_file=<list of CTL files in new location> scope=spfile
    5-alter system set core_dump_dest=<new empty location for cdump> scope=spfile
    6-alter system set user_dump_dest=<new empty location for udump> scope=spfile
    7-alter system set background_dump_dest=<new empty location for bdump> scope=spfile
    (CTL are still in old location but contain information about the new location)
    8-shutdown
    9-copy all .CTL files to the new location
    10-startup
    Many thanks to you all for your help.

  • My MacBook Pro keeps making copies of a document that I am trying to save. I don't want to duplicate the file. I only want to save it on both my hard drive and my external hard drive. I do not want to change its name for every save, which the computer see

    My MacBook Pro keeps making copies of a document that I am trying to save. I don't want to duplicate the file. I only want to save it on both my hard drive and my external hard drive. I do not want to change its name for every save, which the computer seems insistent on doing. Help!!

    11lizzyp wrote:
    can't be saved because the file is read-only.
    I did not create the file to be read-only. I created to be able to continue to add to it as I work on it.
    More on versions here:
    http://support.apple.com/kb/ht4753
    local snapshots:
    http://support.apple.com/kb/HT4878
    Sounds like a permissions problem ie read only.
    If running repair permissions from your DiskUtility.app does not sort it,
    Someone should jump in here with erudite and concise fix.

  • I have many contacts in address book from a certain company that just changed its name.  Is there a way to globally change all the contacts to the new company name all at once?

    I have many contacts in address book from a certain company that just changed its name.  Is there a way to globally change all the contacts to the new company name all at once?

    Rando510 wrote:
    Although clunky as you say, this sounds like a reasonably efficient way to accomplish what I was seeking.
    Address Book has no global find/replace. Bob Grove suggested one possible workaround; however, a grep-capable text editor (eg, TextWrangler) is better than TextEdit if complex strings are involved.
    An alternative is Bento (which is designed specifically to interact with the AB database), but it's not free.

  • My new iMac is seen as my old Mac Pro on the network because I used Migration Assistant. How do I change its name to iMac?

    I used Migration Assistant about 4 months ago to move everything across to my new iMac. Since then instead of being recognised as an iMac it's seen on the network and other places as my Mac Pro.
    How do I change its name to iMac?
    Cheers,
    David
    Mac OS X 10.6.8

    Hello David. Open System Preferences > Sharing. At the top you will see Computer Name and the old Mac Pro name. Highlight this and change to the preferred name.
    Sometimes you also need to use the Edit button under the name. But if you change the name in the first view and then press the Edit button, it should show the new name you just set.

  • HT204074 Our new iphone5 id name is the same as an existing still in use iphone4 in the family; if I remove the devise; change its name can I then immediately associate it with the correct name.

    I have read the HT4627 but I think my original question is more specific  Our new iphone5 id name is the same as an existing still in use iphone4 in the family; if I remove the devise; change its name can I then immediately associate it with the correct name.

    You can change the name of a device on it via Settings > General > About > Name - you shouldn't need to remove the association and then reassociate it.

Maybe you are looking for