Back to Course
Chapter 02 • 02

Modules, Standard Library & Real-World File I/O

12 Lessons • Hands-on practice

01

The `if __name__ == '__main__':` Idiom

When run directly as a script, `__name__` is `'__main__'`. When imported as a module by another file, `__name__` matches the file's module name.

Start
02

Modern Path Manipulation with `pathlib.Path`

`pathlib.Path` provides cross-platform, object-oriented filesystem paths. Join paths intuitively using the division operator: `dir / "sub" / "file.txt"`.

Start
03

Reading Files Safely with `open()` and `with`

Always open files using `with open(path, "r", encoding="utf-8") as f:`. Read full content with `.read()`, or iterate line by line to protect memory.

Start
04

Writing & Appending Files (`"w"` vs `"a"`)

`"w"` mode wipes existing file data to zero bytes immediately on open. `"a"` mode appends new text to the end without deleting past entries.

Start
05

Parsing & Serializing JSON (`json.loads` / `json.dumps`)

`json.loads(str)` parses JSON text into Python dictionaries. `json.dumps(dict)` serializes a Python dictionary into a JSON formatted string.

Start
06

CSV Processing with `csv.DictReader`

`csv.DictReader` reads comma-separated spreadsheet data directly into clean Python dictionaries where column headers serve as dictionary keys.

Start
07

Working with Raw Bytes & Binary Files (`"rb"`, `"wb"`)

Binary files (images, audio, zip archives) cannot be read as text strings. Open with `"rb"` or `"wb"` to read or write immutable `bytes` objects.

Start
08

Character Encodings, UTF-8 vs ASCII

Convert human Unicode strings to wire bytes using `.encode('utf-8')`. Convert wire bytes back to human strings using `.decode('utf-8')`.

Start
09

The Iterator Protocol: `__iter__` and `__next__`

Any object with an `__iter__()` returning self and a `__next__()` that advances state and raises `StopIteration` 🛑 when finished is a valid iterator.

Start
10

Infinite Iterators: `itertools.count` and `itertools.cycle`

`itertools.count(start, step)` produces numbers infinitely ♾️. `itertools.cycle(seq)` loops over a sequence forever like a broken record 🔁.

Start
11

Combining Streams: `itertools.chain` & `zip_longest`

`itertools.chain(a, b)` glues separate iterables into one seamless stream 🔗. `zip_longest` pairs items without truncating the longer list 🗂️.

Start
12

Slicing Lazy Generators: `itertools.islice`

Generators cannot be sliced with `gen[0:5]` because they have no index 🚫. Use `itertools.islice()` to slice lazy streams safely ✂️.

Start