Rename a File using Python

The os module can be used to rename a file using Python:

import os

os.rename(r"Directory path\OLD_file_name.file_type", 
          r"Directory path\NEW_file_name.file_type")

Steps to Rename a File using Python

Suppose that your goal is to rename a text file from “cars” to “trucks

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

Step 1: Capture the path where the file is stored

To start, capture the path where your file is stored.

For demonstration purposes, let’s suppose that a file called “cars” is stored under the following path:

C:\Users\Ron\Desktop\Test\cars.txt

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

Step 2: Rename the file

To rename the file using Python, you’ll need to use os module as follows:

import os

os.rename(r"Directory path\OLD_file_name.file_type", 
          r"Directory path\NEW_file_name.file_type")

In the context of our example:

  • Directory path: C:\Users\Ron\Desktop\Test
  • OLD file name: cars
  • NEW file name: trucks
  • File type: txt

Don’t forget to place “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 script to rename the text file from “cars” to “trucks” is:

import os

os.rename(r"C:\Users\Ron\Desktop\Test\cars.txt", 
          r"C:\Users\Ron\Desktop\Test\trucks.txt")

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

trucks