How to rename a file in Python using os.rename()?

Published on Aug. 22, 2023, 12:17 p.m.

To rename a file in Python, you can use the os.rename() method from the os library. This method takes the current name and new name of the file as its inputs and renames the file. Here’s an example:

import os

old_name = "/path/to/current_file_name.txt"
new_name = "/path/to/new_file_name.txt"
os.rename(old_name, new_name)

This example renames the file located at /path/to/current_file_name.txt to /path/to/new_file_name.txt using os.rename().

Note that if the new name already exists, os.rename() will overwrite it without warning. Also, if an exception occurs during the rename operation, the file may be left in an inconsistent state.

Using os.rename() is useful when you need to rename a file, such as when you want to change the name of a file to better reflect its contents or to avoid naming conflicts.

Tags: