0%

Chapter 5

Reading and Writing Files

Paths from the Project Root

Chapter 2 taught the shell to find a file from its working directory. Python follows the same map.

The editor beside this lesson has opened reading_log.py. Its first lines name three files:

from pathlib import Path

BOOKS_PATH = Path("data") / "books.txt"
REPORT_PATH = Path("reading_report.txt")
HISTORY_PATH = Path("reading_history.txt")

pathlib is part of Python’s standard library, so there is nothing to install. Path gives a filesystem path its own kind of . The / between two path pieces joins them; it does not divide anything.

A path is a name, not the contents

BOOKS_PATH describes data/books.txt. Creating that value does not open the file, check that it exists, or read one byte from it. This distinction is useful: your program can decide which file it wants before it performs any file operation.

The project currently looks like this:

reading_log.py
README.txt
data/
    books.txt

The other two paths do not exist yet. Later lessons will create them.

Relative to what?

None of the three paths starts at a filesystem root. They are project-: Python interprets them from the process’s working directory.

When you run python reading_log.py from the project root, data/books.txt points at the seeded input. If you stand inside data first, the same path would mean data/data/books.txt, which is not there.

That is why Chapter 2’s pwd habit still matters. A path bug often belongs to the place the program was launched, not to the line that later tries to read.

You could paste an such as /Users/you/Downloads/books.txt into the program. It might work on one machine today, then fail when the project moves, when another learner downloads it, or when Windows spells the root differently. Keeping course data inside the project and naming it from the project root makes the whole folder portable.

What has happened immediately after BOOKS_PATH = Path("data") / "books.txt" runs?

Why keep data/books.txt relative to the project root?

The next lesson crosses the boundary from naming books.txt to reading its text.