📂 Organizing Files & Folders Using Python (Shutil & OS) — Part 2
Now that you can navigate paths (Part 1), let's master manipulation: copying backups, moving files to organized folders, renaming, and deleting cleanup data.
📌 Table of Contents (jump links)
- 📑 Copying Files & Directories
- 🚚 Moving Files & Folders
- 🏷️ Renaming Files & Folders
- 🗑️ Deleting Files & Folders (Safe & Unsafe)
📑 Copying Files & Directories
Use shutil (Shell Utilities) to duplicate data.
shutil.copy2(src, dst): Copies file data + metadata (timestamps). Best for backups.shutil.copytree(src, dst): Recursively copies entire folders.
✅ Copying a single file
Scenario: You want to backup report.txt into a backup folder.
import shutil
import os
src = "project/data/report.txt"
dst = "project/backup/report.txt"
# 1. Create destination folder first
os.makedirs("project/backup", exist_ok=True)
# 2. Copy the file (preserves metadata)
shutil.copy2(src, dst)
print("✅ Copied successfully.")
Resulting Structure:
📁 project/
├── 📁 data/
│ └── 📄 report.txt (Original stays here)
└── 📁 backup/
└── 📄 report.txt (New copy created)
🚚 Moving Files & Folders
Moving is used for sorting files. shutil.move handles moving between different folders (and even drives).
➡️ Moving a file into a specific folder
import shutil
src = "project/downloads/image.png"
dst = "project/images/image.png"
shutil.move(src, dst)
print(f"🚚 Moved {src} to {dst}")
Resulting Structure:
📁 project/
├── 📁 downloads/
│ └── (empty) (File is removed from source)
└── 📁 images/
└── 🖼️ image.png (File appears here)
🏷️ Renaming Files & Folders
Renaming is handled by os.rename (or Path.rename). It effectively "moves" a file to the same folder but with a new name.
✏️ Renaming a file
import os
old_name = "project/data/draft.txt"
new_name = "project/data/final_v1.txt"
os.rename(old_name, new_name)
print("🏷️ Renamed file.")
Resulting Structure:
📁 project/
└── 📁 data/
├── ❌ draft.txt (Gone)
└── 📄 final_v1.txt (New Name)
🗑️ Deleting Files & Folders
⚠️ WARNING: Python deletions are permanent. There is no "Undo" or "Recycle Bin."
❌ Deleting a Single File (os.remove)
import os
file_path = "project/temp/junk_data.csv"
if os.path.exists(file_path):
os.remove(file_path)
print("🗑️ File deleted.")
Resulting Structure:
📁 project/
└── 📁 temp/
└── (empty)
🔥 Deleting a Folder & All Contents (shutil.rmtree)
To delete a folder that contains files, os.rmdir will fail. You must use shutil.rmtree.
import shutil
folder_to_nuke = "project/temp_cache"
# Deletes the folder and everything inside it
shutil.rmtree(folder_to_nuke)
print("🔥 Entire directory deleted.")
Resulting Structure:
📁 project/
├── 📁 data/ (Safe)
└── ❌ temp_cache/ (Completely Removed)