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,.suffixand.parenttake them apart.glob("*.txt")looks in one folder, andrglobin every folder below it.shutil.moveandshutil.copy2move or copy one file.copytreeandrmtreehandle whole folders.rmtreedeletes without asking. Print what a script would do before letting it do it.
Collect, then change
Take a list of a folder's contents before moving anything. A folder that changes while you iterate over it can make the loop skip entries or see the new ones.
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.
The explanation opens here once every check passes.