How do i copy and rename a file in python?

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1

Home » Python

Python copy and rename files: Here, we are going to learn how to copy and rename the files in Python using shutil module functions?
Submitted by Sapna Deraje Radhakrishna, on September 30, 2019

Using shutil (shell utilities) module, file operation such as copy, rename, move, etc is very handy. To copy and rename, there are two approaches:

  1. Move the file with new name
  2. Copy and rename file using 'OS' module

1) Move and Rename file

move function

    shutil.move(src, dst, copy_function=copy2)

The above method recursively moves the file from src to dst and returns the destination.

Reminders,

  • If the destination is an existing directory, then the src object is moved inside the given dst.
  • In case the destination already exists and is not a directory, it will be overwritten using os.rename().
  • In case the destination is on the current filesystem, then os.rename() is used. In the case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.
  • The default copy_function is copy2(). Using copy() as the copy_function allows the move to succeed.

Python code for move and rename file

List command:

    -bash-4.2$ ls
    python_samples test test.txt test.txt.copy test.txt.copy2 -

More & rename files:

# Importing the modules
import os
import shutil

# gets the current working dir
src_dir = os.getcwd() 
# defining the dest directory
dest_file = src_dir + "/python_samples/test_renamed_file.txt"

# moving
shutil.move('test.txt',dest_dir)

# listing the files 
print(os.listdir())

os.chdir(dest_dir)

# list of files in dest
print(os.listdir()) 

Output

'/home/sradhakr/Desktop/my_work/python_samples/ test_renamed_file.txt'
['python_samples', 'test', 'test.txt.copy', 'test.txt.copy2']
['.git', '.gitignore', 'README.md', 'src', ' test_renamed_file.txt']

Copy and rename using os and shutil module

In this approach we use the shutil.copy() function to copy the file and os.rename() to rename the file.

# Importing the modules
import os
import shutil

src_dir = os.getcwd() #get the current working dir
print(src_dir)

# create a dir where we want to copy and rename
dest_dir = os.mkdir('subfolder')
os.listdir()

dest_dir = src_dir+"/subfolder"
src_file = os.path.join(src_dir, 'test.txt.copy2')
shutil.copy(src_file,dest_dir) #copy the file to destination dir

dst_file = os.path.join(dest_dir,'test.txt.copy2')
new_dst_file_name = os.path.join(dest_dir, 'test.txt.copy3')

os.rename(dst_file, new_dst_file_name)#rename
os.chdir(dest_dir)

print(os.listdir())

Output

/home/user/Desktop/my_work
['python_samples', 'subfolder', 'test', 'test.txt.copy2', 'test.txt.copy_1']
'/home/sradhakr/Desktop/my_work/subfolder/test.txt.copy2'
['test.txt.copy3']

Summary: shutil (shell utilities module ) is a more pythonic way to perform the file or directory copy , move or rename operations.

Reference: https://docs.python.org/3/faq/windows.html

How do I copy and rename a file?

1. Click the actions drop-down menu next to the file or folder you want to rename. 2. Click the Rename option..
Check the boxes next to the items that you want to copy..
Click the COPY button on the toolbar..
Select the destination folder for your selected items..
Click the OK button..

How do you mass rename a file in Python?

To rename files in Python, use the rename() method of the os module. The parameters of the rename() method are the source address (old name) and the destination address (new name).

How do you copy a file in Python?

Steps to Copy a File using Python.
Step 1: Capture the original path. To begin, capture the path where your file is currently stored. ... .
Step 2: Capture the target path. Next, capture the target path where you'd like to copy the file. ... .
Step 3: Copy the file in Python using shutil. copyfile..

Which method is used to rename a file in Python?

rename() method in Python is used to rename a file or directory.