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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap