How to Rename a File using Python (with examples)

You may use the following template to rename a file using Python:

import os
os.rename(r'file path\OLD file name.file type',r'file path\NEW file name.file type')

Let’s now review an example with the steps to rename a file using Python.

Steps to Rename a File using Python

Suppose that your goal is to rename a text file from “Products” to “Shipped Products.”

Here are the steps that you may follow to rename your file:

Step 1: Locate the file that you want to rename

For example, I stored the “Products” text file inside a folder called Test:

test folder

Step 2: Capture the path where the file is stored

Next, capture the path where your file is stored. In my case, the path where the “Products” file is stored is:

C:\Users\Ron\Desktop\Test

 

How to Rename a File using Python

 

You’ll need to modify the file path to reflect the location where the file is stored on your computer.

Step 3: Rename the file

To rename the file using Python, you’ll need to import the os package.

You can then use the following template to rename your file:

import os
os.rename(r'file path\OLD file name.file type',r'file path\NEW file name.file type')

In the context of our example:

  • File path: C:\Users\Ron\Desktop\Test
  • OLD file name: Products
  • NEW file name: Shipped Products
  • File type: txt

Don’t forget to put “r” before the file path to avoid the following error in Python:

(unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

The complete Python code to rename the text file from “Products” to “Shipped Products” is:

import os
os.rename(r'C:\Users\Ron\Desktop\Test\Products.txt',r'C:\Users\Ron\Desktop\Test\Shipped Products.txt')

Run the code (adjusted to your file path) and you’ll now see the new file name:

Rename a File using Python

Optional Step: Add a Date Stamp when Renaming the File

Let’s say that you want to add a date stamp when renaming the file.

You can accomplish this task using the datetime package.

In our example, to rename the “Products” file to “Shipped Products” + the date stamp, you’ll need to apply this code (adjusted to your file path):

import os
import datetime

Current_Date = datetime.datetime.today().strftime ('%d-%b-%Y')
os.rename(r'C:\Users\Ron\Desktop\Test\Products.txt',r'C:\Users\Ron\Desktop\Test\Shipped Products_' + str(Current_Date) + '.txt')

Run the code, and you’ll get this renamed file with the date:

date stamp python

Few notes about the code:

  • %d-%b-%Y reflects the date format of dd-mmm-yyyy
  • The + symbol is used to concatenate the new file name, the date stamp and the txt file type