Stop 11 · Automation & ScriptingTopics · 2/7

Automating Files & Folders (os, shutil)

Part of the Python Roadmap

In short

Renaming 300 wedding photos, backing up invoices every Friday, clearing out old downloads: jobs that take an afternoon by hand take one second with a short Python script.

os, shutil and pathlib let scripts create, copy, move, rename and delete files and folders. They are the basis for tasks like sorting downloads, backing up folders or renaming hundreds of photos.

The jaadu, dressed as a mover with a cap, carries a stack of labelled boxes from a cluttered room into a neat row of cupboards, ticking items off a clipboard.

Think of it like this

Packers and movers with a checklist

Good packers moving a family from Hyderabad to Pune don't wander around guessing. They follow a list: copy the documents, move the books to box 4, relabel the kitchen boxes, throw out the old newspapers. pathlib and shutil let your script be that tireless crew, working through files exactly as listed.

Watch it happen

A Friday invoice backup

Find
Make folder
Copy
Rename

1/4The script builds the path to Documents/invoices with pathlib, the same way on Windows, Mac and Linux.

The big ideas

What you need to know

pathlib for paths

Path.home() / "Documents" builds paths with /. Methods like .exists(), .suffix, .glob() and .rename() cover most needs.

shutil for heavy lifting

copy2 copies a file with its timestamps, copytree copies a folder, move moves or renames, rmtree deletes a whole folder.

os for the system

os.environ, os.getcwd() and os.listdir() still matter, but for paths, pathlib is the modern, cleaner choice.

Dry run first

Print what you would do before doing it. A wrong rmtree or move can't be undone with Ctrl+Z.

See it in code

Walk through the code

python
1import shutil2from datetime import date3from pathlib import Path4 5source = Path.home() / "Documents" / "invoices"6backup_root = Path.home() / "Backups"7backup_root.mkdir(parents=True, exist_ok=True)8 9target = backup_root / f"invoices-{date.today():%Y-%m-%d}"10shutil.copytree(source, target, dirs_exist_ok=True)11 12renamed = 013for pdf in target.glob("*.pdf"):14    clean_name = pdf.name.lower().replace(" ", "_")15    if clean_name != pdf.name:16        pdf.rename(pdf.with_name(clean_name))17        renamed += 118 19print(f"Backed up to {target}, renamed {renamed} files")

1/4Build paths with the / operator. mkdir with parents=True creates any missing parent folders too.

Works the same on Windows, macOS and Linux, because pathlib handles the slashes for you.

Save yourself the pain

Common mistakes

Oops

Building paths with string concatenation like folder + "\\" + name.

Do this instead

Use pathlib: folder / name. It works on every operating system.

Oops

Running a delete or move script on real files the first time.

Do this instead

Test on a copy of the folder, or add a --dry-run mode that only prints.

Oops

Using os.remove on a folder.

Do this instead

os.remove deletes files. Use Path.rmdir for empty folders and shutil.rmtree for full ones, carefully.

Your mission

Batch-rename holiday photos

~25 min

Quick check

Which call copies an entire folder, including all its subfolders and files?

Go deeper

  1. 1Rename every file in a folder to add today's date as a prefix.
  2. 2Copy a folder as a backup with shutil.copytree.
  3. 3Print what the script would do in a dry-run mode before it actually moves or deletes anything.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge