Python Renaming and Deleting Files – Manage Files Dynamically
Introduction – Why Rename or Delete Files with Python?
When building real-world applications like log rotation, data preprocessing, or automated file maintenance, you’ll often need to rename files or delete them dynamically. Python provides simple and reliable methods to do both using os and pathlib.
In this guide, you’ll learn:
- How to rename files using
os.rename()andpathlib - How to delete files using
os.remove()andPath.unlink() - File existence checks and exception handling
- Real-world use cases and safety tips
1. Rename Files in Python
Using os.rename()
import os
os.rename("old_name.txt", "new_name.txt")
Renames the file or moves it to a new path.
Safe Renaming – Check Existence
import os
old_file = "report.txt"
new_file = "report_2025.txt"
if os.path.exists(old_file):
os.rename(old_file, new_file)
print("File renamed successfully.")
else:
print("Original file not found.")
Tip: Always check if the file exists to avoid FileNotFoundError.
Using pathlib.Path.rename()
from pathlib import Path
Path("data.txt").rename("data_backup.txt")
Cleaner syntax for Python 3.6+.
2. Delete Files in Python
Using os.remove()
import os
os.remove("old_log.txt")
Deletes the specified file.
Using pathlib.Path.unlink()
from pathlib import Path
file = Path("temp.txt")
if file.exists():
file.unlink()
Modern way to remove a file safely.
🚨 3. Handle Rename & Delete Errors Safely
import os
try:
os.rename("sample.txt", "archive.txt")
os.remove("archive.txt")
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print("Unexpected error:", e)
Avoids crashes and logs issues clearly.
4. Real-World Use Case: Rename and Archive Then Delete
import os
from datetime import datetime
filename = "logs.txt"
timestamp = datetime.now().strftime("%Y%m%d")
if os.path.exists(filename):
archived = f"logs_{timestamp}.txt"
os.rename(filename, archived)
print("File renamed.")
# Optional delete after archiving
os.remove(archived)
print("Archived file deleted.")
else:
print("File not found.")
Automate file archival and cleanup.
Tips & Warnings
Use os.path.exists() or Path.exists() before renaming or deleting
Use logging to track renamed/deleted files in automation scripts
Avoid overwriting files during rename without backup
Don’t delete important system files accidentally
Summary – Recap & Next Steps
Python makes it easy to rename and delete files with os.rename(), os.remove(), and the modern pathlib module. Always check for existence and handle exceptions for safer automation.
Key Takeaways:
- Use
os.rename()orPath.rename()to rename files - Use
os.remove()orPath.unlink()to delete files - Always check existence with
os.path.exists()orPath.exists() - Wrap actions in
try...exceptfor error safety
Real-World Relevance:
Used in file rotation, data backups, automation scripts, and log cleanup tools.
FAQ – Python Rename & Delete Files
How do I rename a file in Python?
Use:
os.rename("old.txt", "new.txt")
How do I safely delete a file?
Use:
if os.path.exists("file.txt"):
os.remove("file.txt")
Or with pathlib:
Path("file.txt").unlink()
Can I rename and move a file together?
Yes. Renaming across directories will move the file:
os.rename("file.txt", "backup/file.txt")
What happens if I try to rename a non-existent file?
Raises FileNotFoundError. Always check with os.path.exists() or Path.exists().
Can I undo file deletion?
No. Once deleted with os.remove() or unlink(), recovery isn’t possible via Python alone.
Share Now :
