PythiloLesson 9 of 15 · progress kept in this browser

Tidying files with pathlib

Scripts that sort downloads, rename photos or clean build folders are some of the most common Python anyone writes. pathlib finds and names files, and shutil copies, moves and deletes them.

import shutil
from pathlib import Path

root = Path("demo")
src = root / "src"
src.mkdir(parents=True, exist_ok=True)
(src / "a.txt").write_text("hi")
(src / "b.md").write_text("# b")
shutil.copytree(src, root / "copy",
                dirs_exist_ok=True)
for p in sorted(root.rglob("*.txt")):
    print(p, p.stem, p.suffix)
  • / joins paths. .name, .stem, .suffix and .parent take them apart.
  • glob("*.txt") looks in one folder, and rglob in every folder below it.
  • shutil.move and shutil.copy2 move or copy one file. copytree and rmtree handle whole folders.
  • rmtree deletes without asking. Print what a script would do before letting it do it.
Your task

Write tidy(folder), taking a string or a Path, that moves each file directly inside folder into a subfolder named after its suffix, lowercased and without the dot (photo.JPG goes to jpg), and files with no suffix into other. Leave existing subfolders alone, and return a dict counting the files moved into each subfolder.