1

I'm trying to duplicate a file in python.

Going through shutil, I've only found solutions to copy and move the files but I need to duplicate a file to rename and keep the original.

    photos54_TempString = "photos54/thumb-" + artistName + "_54.jpg"
    photos54_NewString = "quickManik_Music/" + songID + "-" + 
    artistName + "_54.jpg"

    copyfile(photos54_TempString, photos54_NewString)
7
  • 11
    Can you explain how what you want to do is different from "copy"? Commented Jun 26, 2017 at 20:38
  • 4
    I.e. what about shutil.copy(photos54_TempString, photos54_NewString) is incorrect? Commented Jun 26, 2017 at 20:39
  • 2
    @ManikKhurana No, you've described the behavior of "move". "Copy" is similar, but it keeps the original file intact. Commented Jun 26, 2017 at 20:41
  • 2
    @ManikKhurana That would be shutil.move Commented Jun 26, 2017 at 20:41
  • 2
    no, that is move. copy duplicates and keeps original Commented Jun 26, 2017 at 20:41

1 Answer 1

2

Use the function shutil.copyfile.

Here's an example, using the terminal and the Python interpreter:

$ cd /tmp
$ touch myfile
$ python3
Python 3.5.3 (default, May 10 2017, 15:05:55) 
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.copyfile('myfile', 'mysecondfile')
'mysecondfile'
>>> 
$ ls my*
myfile  mysecondfile
Sign up to request clarification or add additional context in comments.

2 Comments

The comments under my post explain the answer. Since I want to keep the original I have to use shutil.copy() rather than shutil.copyfile()
@ManikKhurana No, shutil.copy and shutil.copyfile work the same in that regard. However, copy does also copy the file's permissions, while copyfile doesn't. It's shutil.move that doesn't keep the original, i.e. it moves the original to a new location.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.