Chapter 7
Files, Paths, and Modules
Reading text files, writing text files, paths, context managers, modules, imports, main blocks, and small project layout.
What this chapter does
Small programs usually read input, compute a result, and write output. This chapter teaches the file and module habits needed to move from isolated snippets to script-shaped work.
Lessons
Read these in order.
The chapter opening gives the main idea. Move through these lessons next; each page reuses ideas from the pages before it.
- 01Reading Text Files
Opening files in read mode, reading text, reading lines, and converting near the boundary.
- 02Writing Text Files
Write mode, append mode, string conversion, and explicit newlines.
- 03Paths
Relative paths, current working directories, pathlib, and creating folders before writing.
- 04Context Managers
Using with blocks to open files briefly and release resources reliably.
- 05Modules and Imports
Modules as Python files, import styles, and keeping reusable functions separate from scripts.
- 06Main Blocks
The standard script entry-point pattern and why imported modules should not surprise callers.
- 07Small Project Layout
Separating data, output, reusable functions, and the script that runs the workflow.
You are ready when
- Read a text file and convert its contents near the boundary.
- Write small summary files.
- Build paths with pathlib.
- Use with blocks for file cleanup.
- Import modules and keep reusable functions separate from scripts.
- Use a main block for script entry points.
Where this leads
- Small Objects, Records, and Type Hints
- NumPy Arrays
- Small Numerical Experiments