How to Rename a File in Python

  1. Rename a File in Python Using os.rename()
  2. Rename a File in Python Using shutil.move()
How to Rename a File in Python

If you wish to rename a file in Python, choose one of the following options.

  1. Use os.rename() to rename a file.
  2. Use shutil.move() to rename a file.

Rename a File in Python Using os.rename()

The function os.rename() can be used to rename a file in Python.

For example,

Python
 pythonCopyimport os

file_oldname = os.path.join("c:\\Folder-1", "OldFileName.txt")
file_newname_newfile = os.path.join("c:\\Folder-1", "NewFileName.NewExtension")

os.rename(file_oldname, file_newname_newfile)

In the above example,

file_oldname - the old file name.

file_newname_newfile - the new file name.

Result:

  1. The file named file_oldname is renamed to file_newname_newfile
  2. The content which was present in file_oldname will be found in file_newname_newfile.

Pre-requisites:

Rename a File in Python Using shutil.move()

The function shutil.move() can also be used to rename a file in Python.

For example,

Python
 pythonCopyimport shutil

file_oldname = os.path.join("c:\\Folder-1", "OldFileName.txt")
file_newname_newfile = os.path.join("c:\\Folder-1", "NewFileName.NewExtension")

newFileName = shutil.move(file_oldname, file_newname_newfile)

print("The renamed file has the name:", newFileName)

In the above example,

file_oldname: the old file name.

file_newname_newfile: the new file name.

Result:

  1. The file named file_oldname is renamed to file_newname_newfile
  2. The content which was present in file_oldname will now be found in file_newname_newfile.
  3. The return value - newFileName, which is the new file name.

Pre-requisites:

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Related Article - Python File