πŸ“‚ Python File Handling
Estimated reading: 3 minutes 22 views

πŸ”„ 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() and pathlib
  • How to delete files using os.remove() and Path.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() or Path.rename() to rename files
  • βœ… Use os.remove() or Path.unlink() to delete files
  • βœ… Always check existence with os.path.exists() or Path.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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Renaming and Deleting Files

Or Copy Link

CONTENTS
Scroll to Top