Python Copy file & Rename Files in Folder

This is a simple code snippet that I developed for one my recent project. This code reads list of file names from a CSV file. Then copies to a new destination path and rename file in Python itself.

The Excel/CSV file is designed in a way tha the first columns has list of files in a folder & secondcolumns has new name that each file has to be renamed.

The Python code in this page will first use Pandas to read the content from csv file. Then performs copy  operation on the files to a new folder. Then, at last, renames each files as per the specification in the CSV file.

Method 1: Python Code to Copy Files to New Folder and Rename

Apart from Pandas, this function used in this Python program is os.rename that does the core function.

Here is the code that rename a file in Python.

import shutil, os
import pandas as pd 

# Set Src & Dest Path
src_path = 'D:/folder/'
dest_path = 'D:/Newfolder/'

# Read from CSV File
df = pd.read_csv('nameslist.csv')
images = df.oldname
nImages = df.newname

# Make Folder if does not exist
os.makedirs(dest_path ,exist_ok=True)

# Loop Thru each Image File
i = 0
for img in images:
        print(str(img) + ' --> ' + nImages[i])
        shutil.copy( src_path + str(img) + '.jpg',dest_path)
        os.rename (dest_path + str(img) + '.jpg' , dest_path +  nImages[i] + '.jpg' )
        i = i + 1
        
print('Done!')

For renaming shutil is used and to read csv file pandas library is used.

This is just a simple and straight forward coding. That loops thru each row in CSV and processes the files one by one. Pretty much self explanatory.

Just create the csv with two column headers.

  1. oldname
  2. newname

So that the values in these columns gets populated correctly in the Python list.

Method 2: Rename a file in Python

There is an alternate methods available in Python to rename a file. You can also use ‘shutil’ module also.

Here is the code that renames the file.

# Rename a file in Python using shutil.move
import shutil
shutil.move("old_file_name.txt", "new_file_name.txt")

One important note is that, it is better to use these rename functions inside a ‘try’ command. In case if there is a file already present with same name as new file name, then we can catch the exception and handle it accordingly.

External References:

  1. How to rename a file in Python?

Leave a Reply