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: 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 “Products” is stored under the following path:
C:\Users\Ron\Desktop\Test
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 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 get the new file name:
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:
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