Automating File & Folder Tasks
Automate common file tasks — renaming, organizing, copying, archiving. Use os, shutil, and pathlib for powerful file system automation.
15 min•By Priygop Team•Updated 2026
File Automation
File Automation
import os
from pathlib import Path
from collections import defaultdict
# Common automation tasks:
# 1. Batch rename files
def demo_rename():
files = ["photo_001.jpg", "photo_002.jpg", "photo_003.jpg"]
print("=== Batch Rename Demo ===")
for i, f in enumerate(files, 1):
new_name = f"vacation_{i:03d}{Path(f).suffix}"
print(f" {f} → {new_name}")
demo_rename()
# 2. Find duplicate files (by name)
def find_duplicates(files):
seen = defaultdict(list)
for f in files:
name = Path(f).stem
seen[name].append(f)
duplicates = {k: v for k, v in seen.items() if len(v) > 1}
return duplicates
test_files = ["doc.txt", "photo.jpg", "doc.txt", "report.pdf", "photo.jpg"]
dupes = find_duplicates(test_files)
print("\n=== Duplicate Files ===")
for name, files in dupes.items():
print(f" '{name}' appears {len(files)} times")
# 3. Organize by extension
def organize_plan(files):
categories = defaultdict(list)
for f in files:
ext = Path(f).suffix.lower()
categories[ext].append(f)
return categories
mixed = ["data.csv", "photo.png", "script.py", "report.pdf",
"image.jpg", "app.py", "notes.txt"]
plan = organize_plan(mixed)
print("\n=== Organization Plan ===")
for ext, files in sorted(plan.items()):
print(f" {ext}: {', '.join(files)}")
# 4. Monitor directory size
def calc_sizes(files_with_sizes):
total = sum(s for _, s in files_with_sizes)
print(f"\n=== Directory Stats ===")
print(f" Files: {len(files_with_sizes)}")
print(f" Total: {total / 1024:.1f} KB")
data = [("app.py", 4096), ("data.csv", 102400), ("image.png", 51200)]
calc_sizes(data)Tip
Tip
Use struct.pack/unpack for binary data. Use json for text-based serialization. Use Protocol Buffers for high-performance serialization.
Diagram
Loading diagram…
Everything in Python is an object — use type() to check
Common Mistake
Warning
Not handling encoding issues. Use encoding='utf-8' explicitly. response.encoding may not always be correct.
Quick Quiz
Practice Task
Note
(1) Encode/decode text with different encodings. (2) Handle binary data with base64. (3) Parse XML with ElementTree.