Python – Copy , Rename List of Files in Folder

CSV File List – Rename Files in Folder Using Python

This is a simple code snippet that I developed for one my recent project.

The current name of list of files in a folder is given in a CSV file. Also the new name that each file has to be renamed is given in next column.

The Python code in this page will copy the files to a new folder. And also renames each files as per the specification in the CSV file.

Python Code to Copy Files to New Folder and Rename

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

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.