Skip to content

Working with Paths and the Filesystem

Beginning of the lesson

Working with Paths and the Filesystem

Build, inspect and traverse file paths portably with pathlib and os

Big idea: In the beginner course you opened a file by hard-coding its name. Real programs rarely know the exact path ahead of time: they build it from pieces, check whether it exists, list what is in a folder, and walk whole directory trees. Python's modern tool for this is pathlib.Path - an object that treats a path as structured data rather than a fragile string. The older os module still fills a few gaps, so you will meet both.
By the end you will be able to:
  • explain why joining paths with "+" and "/" breaks across operating systems,
  • build paths safely with Path and the / operator,
  • read a path apart with .name, .stem, .suffix, .parent and .parts,
  • test existence and type with .exists(), .is_file(), .is_dir(),
  • create folders with .mkdir(parents=True, exist_ok=True),
  • list and filter directory contents with .iterdir(), .glob() and .rglob(),
  • walk an entire folder tree and know when to reach for os instead.

1. The problem: paths are not just strings

A path looks like an ordinary string, so the tempting first instinct is to glue pieces together with +:

folder = "data"
name = "report.txt"
path = folder + "/" + name      # "data/report.txt" - fragile!

This works by luck, not by design. Two real problems hide in it:

  • Separators differ. Linux and macOS separate folders with a forward slash /; Windows uses a backslash \. Hard-coding one breaks the other machine.
  • Edge cases pile up. Does folder already end with a slash? Is a part empty? String maths forces you to handle each case by hand, and one missed case corrupts the path.

pathlib solves this by making a path an object that knows how to join, split and compare itself correctly on whatever operating system it runs on.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers