IntermediateLesson firstCategory 16 of 20

File Paths (os & pathlib)

Navigate and manipulate file system paths. Read the lesson first, then move through the exercises in order.

8 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Path Parsing Objects

Study Material

Read the full lesson

Paths: relative vs absolute

A relative path starts from the current folder. An absolute path starts from the drive root.

Joining paths safely

Use os.path.join() so your code works on Windows, macOS, and Linux.

python
import os path = os.path.join("data", "notes.txt") print(path)

pathlib gives you a clean, object-style way to work with paths.

python
from pathlib import Path path = Path("data") / "notes.txt" print(path)

Checking if a path exists

python
from pathlib import Path path = Path("data") / "notes.txt" print(path.exists())

Listing files in a folder

python
from pathlib import Path for p in Path("data").iterdir(): print(p.name)

Creating folders

python
from pathlib import Path Path("output").mkdir(exist_ok=True)

Common mistakes to avoid

  • Building paths with string +.
  • Using backslashes directly (\\) instead of Path() or os.path.
  • Assuming a file exists without checking.

What you should understand after this lesson

  • The difference between relative and absolute paths.
  • How to build paths safely with os.path or pathlib.
  • How to check for files and folders.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.