25: How to rename a file using Python Program

In order to rename a file using Python, you can make use of the os.rename method from the os module.

 os.rename(old_filename, new_filename)

Program:
'''
Rename a file in Python

Author  : Code2care.org
Version : v 1.0
Date    : 3 July 2023 

'''

import os

def rename_file(old_filename, new_filename):
    try:
        os.rename(old_filename, new_filename)
        print(f"{old_filename} renamed to {new_filename} successfully.")
    except OSError as error:
        print(f"Error occurred while renaming the file: {old_filename}", error)

old_file_name = 'data_draft.csv'
new_file_name = 'data_2023.csv'

rename_file(old_file_name, new_file_name)

Note: If the destination file already exists a FileExistsError is always raised.

Rename a file using Python Code

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!