π 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...except
for 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 :