Lesson 36 of 41
Filesystem Automation: pathlib, os & shutil for Batch File Processing
Overview & Learning Objectives
Data analysts spend countless hours manually downloading, renaming, unzipping, and sorting weekly spreadsheets into nested client folders. Python’s modern `pathlib` module provides an object-oriented approach to filesystem navigation that works cross-platform across Windows, macOS, and Linux without fragile string slicing. Paired with `shutil` for file copying and archival, analysts can automate complete local data staging directories.
- Navigate and inspect directory trees using modern `pathlib.Path` objects and path arithmetic (`path / "subdir"`).
- Batch discover target data files using wildcard pattern matching (`Path.glob("*.csv")` and `rglob()`).
- Move, copy, archive, and organize processed files programmatically using `shutil`.
Industry Standard
Standard: Analytics engineering teams at Deloitte and PwC automate quarterly audit intake by building Python watchdogs that ingest incoming client CSV drops, validate schemas, and archive raw files.
Real-World Example: ScoopCraft Dark-Store Weekly POS File Archival
ScoopCraft automatically ingests 15 dark-store CSV drops from an `/incoming` SFTP folder, merges them into a master database, and moves processed files to an `/archive/YYYY-MM/` directory.
| Source File | Store ID | File Size | Target Action | Destination Path |
|---|---|---|---|---|
| pos_koramangala_20261112.csv | BLR-01 | 1.4 MB | Ingested & Archived | /archive/2026-11/pos_blr01_processed.csv |
| pos_indiranagar_20261112.csv | BLR-02 | 1.8 MB | Ingested & Archived | /archive/2026-11/pos_blr02_processed.csv |
| pos_whitefield_20261112.csv | BLR-03 | 950 KB | Ingested & Archived | /archive/2026-11/pos_blr03_processed.csv |
| corrupted_pos_file.tmp | UNKNOWN | 0 KB | Quarantined | /quarantine/corrupted_pos_file.tmp |
Syntax & Core Code Implementation
from pathlib import Path
import shutil
import pandas as pd
from datetime import datetime
# Initialize directory paths
base_dir = Path('./data_pipeline')
incoming = base_dir / 'incoming'
archive = base_dir / 'archive' / datetime.now().strftime('%Y-%m')
archive.mkdir(parents=True, exist_ok=True)
# Discover all CSV files recursively
csv_files = list(incoming.glob('*.csv'))
print(f"Found {len(csv_files)} files to process.")
dfs = []
for file_path in csv_files:
if file_path.stat().st_size == 0:
print(f"Skipping empty file: {file_path.name}")
continue
df = pd.read_csv(file_path)
df['source_file'] = file_path.name
dfs.append(df)
# Archive processed file
target_dest = archive / file_path.name
shutil.move(file_path, target_dest)
print(f"Archived {file_path.name} -> {target_dest}")
if dfs:
master_df = pd.concat(dfs, ignore_index=True)
master_df.to_parquet(base_dir / 'master_daily_sales.parquet')
Parameters & Arguments Breakdown
Path(path_str): Creates a Path object representing a file or directory path.path.glob(pattern): Matches all files in directory satisfying glob pattern (e.g. "*.csv").path.rglob(pattern): Recursively searches through all nested subdirectories for matching files.shutil.move(src, dst): Atomically moves a file or directory to another destination path.
Step-by-Step Implementation
- Define Base Directories: Initialize paths via `Path("path/to/folder")` and ensure destinations exist using `mkdir(parents=True, exist_ok=True)`.
- Match Target Files: Collect target files using `path.glob("*.csv")` and filter out zero-byte corrupted files.
- Process and Archive: Read data into Pandas, execute downstream analytics, and cleanly move raw files into dated archive folders via `shutil.move()`.
Common Mistakes & Limitations
- Using manual string concatenation (e.g. `folder + "/" + file`) which fails on Windows due to backslash path separators; always use `Path / file`.
- Using `os.mkdir()` without `exist_ok=True`, throwing `FileExistsError` if the folder already exists.
- Deleting files with `os.remove()` inside an untested script before confirming successful database insertion.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Copy as Path in Windows Explorer | Shift + Right Click | — |
| Copy pathname in macOS Finder | — | Cmd + Option + C |
Pro Tips & Modern Best Practices
- Use `path.stem` to get the filename without extension (e.g. `"sales"` from `"sales.csv"`) and `path.suffix` to inspect extension (`".csv"`).
- Use `shutil.make_archive("backup", "zip", "data_dir")` to bundle an entire directory into a compressed zip file in one line.