File Rename in Python
Rename a file using the os module.
BeginnerFile Handling ProgramsExample 9 of 20
file-rename.py
1# 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.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.