Modules, Standard Library & Real-World File I/O
12 Lessons • Hands-on practice
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.
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"`.
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.
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.
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.
CSV Processing with `csv.DictReader`
`csv.DictReader` reads comma-separated spreadsheet data directly into clean Python dictionaries where column headers serve as dictionary keys.
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.
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')`.
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.
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 🔁.
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 🗂️.
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 ✂️.