How to Rename a File In Python

In this tutorial, we will learn how to rename a file name in Python. We will use Python standard module to rename our file.

Rename File In Python

To rename our file, we can use either rename() or replace() method of os module. You don’t need to install the os module. It’s preinstalled with Python.

First import os module, then assign two variables one with file address and another one with file destination. Don’t put your path without double slashes otherwise, you will get an error.

Rename the file using the rename() method

The method used in the below code takes two mandatory arguments file source and file destination.

import os
filePath = "C:\\Users\\Public\\Pictures\\myfile.txt"
fileDst= "C:\\Users\\Public\\Pictures\\myfile2.txt"
os.rename(filePath,fileDst)


Rename the file using the replace() method

import os
filePath = "C:\\Users\\Public\\Pictures\\myfile.txt"
fileDst= "C:\\Users\\Public\\Pictures\\myfile2.txt"
os.replace(filePath,fileDst)

You can use any one of the two methods to rename your file.

Leave a Reply

Your email address will not be published.