Python automation and practical scripting · Lesson 1 of 3
Automate files and folders with pathlib and shutil
Build a safe file-organizing script with previews, filters, and collision handling.
Lesson
1. Concept and mental model
Python is effective for repetitive file tasks because pathlib can discover paths and shutil can copy or move them. First state the task precisely: which directory is in scope, what file patterns are eligible, where results go, and how collisions are handled. Avoid broad operations rooted at the current working directory; resolve an explicit configured path and verify it is the intended location.
2. How it works
Start with a dry run that prints each proposed action without changing files. Review the plan, then enable changes deliberately. Check whether a destination already exists and decide whether to skip, rename, or require confirmation; silently overwriting a file can destroy data. If a batch can partially fail, report completed and failed items so an operator can recover instead of assuming the whole task was atomic.
3. Use it safely and effectively
Test file automation using a temporary directory populated with representative cases: nested folders, spaces and Unicode in names, empty files, duplicate destinations, and unexpected extensions. Do not follow symlinks blindly when the task must stay within a trusted directory. Log file names and outcomes without exposing sensitive file contents. A useful automation script is repeatable: running it twice should not produce surprising duplicate or destructive effects.
4. Syntax reference
from pathlib import Path
root = Path('inbox').resolve()
for path in root.glob('*.csv'):
print(f'Would process: {path.name}')5. Guided walkthrough
Resolve one explicit input directory, filter only the files the task is allowed to change, and print the proposed destination before applying any move. Check for existing destinations and report each outcome so rerunning the script does not silently overwrite files.
6. Common mistakes to avoid
- Testing a file mover directly on important data without a dry run or backup.
- Ignoring collisions and letting a move overwrite or misplace a file.
Visual guide
Safe file automation
-
Step 01
Scope
Resolve and validate the target directory.
-
Step 02
Preview
List planned operations without changes.
-
Step 03
Apply
Handle collisions and report every result.
Code examples
from pathlib import Path
root = Path('inbox').resolve()
for path in root.glob('*.csv'):
print(f'Would process: {path.name}')
Prints a preview of matching CSV files without modifying them.
from pathlib import Path
source = Path('report.csv')
destination = Path('archive') / source.name
if destination.exists():
print('Skip: destination already exists')
else:
print(f'Would move {source} to {destination}')
Prints a preview or skips an existing destination.
from pathlib import Path
import shutil
source = Path('input.txt')
target = Path('backup') / source.name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, target)
print(target.exists())
True
Key points
- Build a safe file-organizing script with previews, filters, and collision handling.
- Prefer explicit, testable behavior over hidden side effects.
- Validate assumptions at system boundaries and handle failure deliberately.
Check your understanding
Practice
Your learning progress