Home > Blockchain >  Is there a way, in python, I can copy a file in a directory and duplicate it in the same directory w
Is there a way, in python, I can copy a file in a directory and duplicate it in the same directory w

Time:01-19

I want to be able to take a file and duplicate it in the same directory with a different name, but I can't figure out how to change the name while copying so it doesn't give me and error that the file already exists or changes the name of the original file.

CodePudding user response:

shutil.copy() can do that if you specify the destination filename as well as destination folder:

import shutil
shutil.copy(r'c:\temp\file1.txt', r'c:\temp\file2.txt')

CodePudding user response:

Adding on to TessellatingHeckler's answer, if you have a file with an arbitrary directory, you can use os.path.dirname and os.path.join to create a new filename in the same directory:

import os
import shutil

original = r'c:\temp\file1.txt'
original_dir = os.path.dirname(original)          # r'c:\temp'
new_name = 'file2.txt'
new_path = os.path.join(original_dir, new_name)   # r'c:\temp\file2.txt'

shutil.copy(original, new_path)

You could of course do that more compactly if you wish. You'll also notice from the shutil.copy() docs that shutil features multiple different copying methods, each one with pros and cons. For example, shutil.copy2() attempts to preserve metadata. It's up to you to decide which method is best for your situation.

  •  Tags:  
  • Related