Python ยท Chapter 37 of 45

OS & Paths

The `os` and `pathlib` modules interact with the file system: list files, check paths, create folders, join paths portably.

`pathlib.Path` is the modern object-oriented way and is preferred over string-based `os.path` today.

pathlib basics

`Path('data') / 'file.csv'` joins paths with `/`. `.exists()`, `.is_file()`, `.mkdir()`, `.read_text()` are common methods.

os essentials

`os.getcwd()` current directory, `os.listdir(path)` list files, `os.environ` environment variables.

Example 1 (python)
from pathlib import Path
p = Path("notes") / "hello.txt"
p.parent.mkdir(exist_ok=True)
p.write_text("Hi!")
print(p.read_text())
Output
Hi!

Create a folder, write, then read a file with pathlib.

Example 2 (python)
import os
print(os.getcwd())
print(os.environ.get("HOME", "unknown"))
Output
/home/user
/home/user

os.getcwd + reading an env var.

Key points

  • `pathlib.Path` is the modern choice.
  • Use `/` to join paths.
  • `os.environ` reads environment variables.
  • Never hard-code `\` or `/` separators โ€” let the library decide.
๐Ÿ’ก Note: Prefer `pathlib` over `os.path`. It's shorter, safer and works identically on Windows, macOS and Linux.

๐Ÿ“ Quick Quiz

1. The modern OO path library is:

2. Which reads an environment variable?

3. In pathlib, `Path('a') / 'b'`: