File Rename

Rename a file using the os module.

PythonBeginner
Python
# Program to rename a file

import os

old_name = input("Enter current filename: ")
new_name = input("Enter new filename: ")

try:
    os.rename(old_name, new_name)
    print(f"Renamed {old_name} to {new_name}")
except FileNotFoundError:
    print("File not found.")

Output

Enter current filename: old.txt
Enter new filename: new.txt
Renamed old.txt to new.txt

os.rename changes the filename at the filesystem level, raising FileNotFoundError if the source is missing.