File Rename in Python
Rename a file using the os module.
BeginnerFile Handling ProgramsExample 9 of 20
file-rename.py
Run in browser1# Program to rename a file23import os45old_name = input("Enter current filename: ")6new_name = input("Enter new filename: ")78try:9 os.rename(old_name, new_name)10 print(f"Renamed {old_name} to {new_name}")11except FileNotFoundError:12 print("File not found.")
Output
Enter current filename: old.txt Enter new filename: new.txt Renamed old.txt to new.txt
What's going on
os.rename changes the filename at the filesystem level, raising FileNotFoundError if the source is missing.