Chapter 7

Files, Paths, and Modules

Reading text files, writing text files, paths, context managers, modules, imports, main blocks, and small project layout.

Subject
Python
Lessons
7 lessons
Practice
12 checks
Review
3 pages

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.

  1. 01
    Reading Text Files

    Opening files in read mode, reading text, reading lines, and converting near the boundary.

  2. 02
    Writing Text Files

    Write mode, append mode, string conversion, and explicit newlines.

  3. 03
    Paths

    Relative paths, current working directories, pathlib, and creating folders before writing.

  4. 04
    Context Managers

    Using with blocks to open files briefly and release resources reliably.

  5. 05
    Modules and Imports

    Modules as Python files, import styles, and keeping reusable functions separate from scripts.

  6. 06
    Main Blocks

    The standard script entry-point pattern and why imported modules should not surprise callers.

  7. 07
    Small Project Layout

    Separating data, output, reusable functions, and the script that runs the workflow.

  1. Conclusion

    The read-compute-write pattern that prepares for records, arrays, plots, and experiments.

  2. Review

    A compact review of file modes, paths, with blocks, imports, main blocks, and small layouts.

  3. Exercises

    Chapter-level practice for reading, writing, paths, imports, and main blocks.

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

Chapter progress