Module 08 · Lesson 02
Paths and Folders with pathlib
Work with files and folders through Path objects: build paths with /, read their parts, check what exists, create folders, list and search them, and read or write a file in one call.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Join paths with /
- Take a path apart
- List a folder in order
- Watch a save file appear
Paths as objects
`pathlib` turns a file's address into an object that knows its name, its folder and whether it exists.
Path()
Path("notes") / "today.txt"joins parts with/, on any computer.Its parts
.name,.stem,.suffixand.parenttake a path apart.Ask first
.exists(),.is_file()and.is_dir()answer True or False and never crash.One-call files
write_text()andread_text()open, work and close in one line.
Paths everywhere
Any program that tidies, backs up or saves files is working with paths.
- Photo appsChange
IMG_001.jpegintoIMG_001.pngwithwith_suffix(). - BackupsFind every
.txtin a folder withglob("*.txt")and copy it. - Game savesMake a
savesfolder the first time the game runs. - DownloadsSort a messy Downloads folder by each file's
.suffix.
Building a path
This line describes where a file lives. Tap each part to see its job.
Part 1 of 6
path:A Path object. Nothing is created on disk yet; it is only an address.
Work with paths
Pick an example, change it, then press Run. Say what you expect to see before you press. Each Run starts with no files, so every example writes its own.
Example 1 of 6Build a path
/ joins parts. as_posix() shows the path with forward slashes on every computer.
Your turn: Add one more folder, live, between rock and the file.
from pathlib import Path
folder = Path("music")
song = folder / "rock" / "track01.mp3"
print(song.as_posix())
print(song.name)
print(song.parent.as_posix())Press Run to see what it prints.Watch a save file appear
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- from pathlib import Path
- base = Path("game")
- save = base / "slot1.txt"
- base.mkdir(exist_ok=True)
- save.write_text("stage 3", encoding="utf-8")
- print(save.exists(), save.suffix)
- print(save.read_text(encoding="utf-8"))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.The name without its ending:
from pathlib import Path
print(Path("songs/intro.mp3").stem)0 of 6 answered
Common pathlib misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
from pathlib import Path
p = Path("data") / "scores.txt" # join parts
p.name, p.stem, p.suffix, p.parent # parts
p.with_suffix(".bak") # new path, other extension
p.exists(), p.is_file(), p.is_dir()
Path("a/b").mkdir(parents=True, exist_ok=True)
p.write_text("hi\n", encoding="utf-8")
p.read_text(encoding="utf-8")
sorted(Path("data").iterdir()) # entries, sorted
sorted(Path("data").glob("*.txt")) # matches, sortedPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Organising downloads by type
A downloads folder holds a mix of files. Create it with sample files, then report how many files there are of each extension.
from pathlib import Path
downloads = Path("downloads")
downloads.mkdir(exist_ok=True)
for name in ["cv.pdf", "cat.jpg", "notes.txt", "dog.jpg", "plan.pdf", "todo.txt", "song.mp3"]:
(downloads / name).write_text("sample", encoding="utf-8")
counts = {}
for entry in sorted(downloads.iterdir()):
counts[entry.suffix] = counts.get(entry.suffix, 0) + 1
for suffix in sorted(counts):
print(suffix, counts[suffix])Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Expecting a sorted folder listing
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
for f in Path("pics").iterdir():
print(f.name)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Retail analytics
Collecting monthly sales files
A chain of shops drops one sales file per branch into dated folders. Each morning a script gathers every branch file in every month folder and totals them.
Why Python fits
The pattern
**/*.txtsearches every month folder at once, so a new month needs no code change.parent.nameandstempull the month and branch out of the path itself.Pythonfrom pathlib import Path for month, branch, amount in [("2024-05", "north", 120), ("2024-05", "south", 80), ("2024-06", "north", 150)]: folder = Path("sales") / month folder.mkdir(parents=True, exist_ok=True) (folder / f"{branch}.txt").write_text(f"{amount}\n", encoding="utf-8") total = 0 for path in sorted(Path("sales").glob("**/*.txt")): amount = int(path.read_text(encoding="utf-8")) print(path.parent.name, path.stem, amount) total += amount print("Total:", total)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why does my path print with backslashes?
Do I still need open() if I use pathlib?
How do I get the extension without the dot?
Can a Path point at a folder that does not exist yet?
Is it safe to delete files with unlink?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 10 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.