Check files and test behaviour
You have brought several small skills together. You can read a function, run it, inspect a change and follow JSON across a boundary. To finish Python and Roots, I want you to use those skills on a file reader whose results you can check repeatedly.
Our requirement is specific: read a JSON list of chapter titles from a known file, return a Python list of text values, and report missing or unsuitable data honestly. We will also check that reading the file does not change it.
To verify that requirement, you will:
- Resolve a path and read its contents safely.
- Check the shape of the parsed data.
- Use tests to challenge both a correct result and an expected failure.
Give the file an address and an encoding
Create chapters.json in your own book-work folder with these public titles:
["Python and Roots", "Python and Branches"]
Save it as UTF-8, a common encoding that maps text characters to bytes. An encoding matters because a file stores bytes; the reader needs a rule for interpreting them as text.
Python's pathlib module gives you a Path, an object representing a filesystem path:
from pathlib import Path
path = Path("chapters.json")
text = path.read_text(encoding="utf-8")
print(text)
This relative path starts from the process's working folder. It does not automatically start from the folder containing the Python source file. If the file is missing, check the working folder before changing the data or suppressing the error.
The / operator can join paths, as in Path("data") / "chapters.json". Here it combines path parts; it is not numerical division. You will see the same form in the tests below.
Keep cleanup attached to the work
A file can also be opened and read through a file object. Use with to keep cleanup attached to the operation:
import json
from pathlib import Path
path = Path("chapters.json")
with path.open("r", encoding="utf-8") as handle:
titles = json.load(handle)
print(titles)
"r" opens for reading. as handle gives a name to the open file object. The indented block uses it, and leaving the with block closes it, including when an exception interrupts the block. This is a context manager, an object that manages entering and leaving an operation.
json.load reads JSON from the open file. A malformed document raises JSONDecodeError; a missing file raises FileNotFoundError. Those failures describe different causes. Returning an empty list for both would hide useful information and could make a broken catalogue look legitimately empty.
Writing needs additional care. Opening an existing file with "w", or using Path.write_text, replaces its contents. "x" creates a new file and fails if it already exists. Choose the mode according to the requirement, not according to the first example an AI finds.
Check the data after parsing it
Save this reader in chapter_index.py:
import json
def load_titles(path):
with path.open("r", encoding="utf-8") as handle:
titles = json.load(handle)
if not isinstance(titles, list):
raise ValueError("Expected a list of titles")
for title in titles:
if not isinstance(title, str):
raise ValueError("Every title must be text")
return titles
isinstance(value, type) checks whether a value is an instance of the named type. This reader first checks the outer list and then each title. It accepts an empty list because our stated requirement permits a list with no entries. A different requirement might reject that case explicitly.
The function does not catch every exception. It reports missing files, malformed JSON and unsuitable data. The part of a real solution that knows how to respond can handle the expected failure, as you learned in the function lesson.
Let a test compare intention with behaviour
A test arranges an input, runs some code and compares what happened with an expected result. pytest is the test runner added in the dependency lesson. Save this as test_chapter_index.py beside the reader:
from chapter_index import load_titles
def test_reads_titles_without_changing_file(tmp_path):
path = tmp_path / "chapters.json"
original = '["Python and Roots", "Python and Branches"]'
path.write_text(original, encoding="utf-8")
titles = load_titles(path)
assert titles == ["Python and Roots", "Python and Branches"]
assert path.read_text(encoding="utf-8") == original
assert fails the test if its condition is false. The first check proves the returned titles; the second checks that reading did not change the file.
tmp_path is a fixture, a value pytest prepares for a test that requests it by parameter name. This built-in fixture provides a temporary folder for that test. pytest supplies it; you do not call the test yourself with an invented path. Later, you will meet the decorator used to define your own fixtures.
Run the tests through the intended environment:
uv run python -m pytest -q
-m pytest asks that Python interpreter to run the pytest module. -q makes the report quieter. A passing result means these particular assertions held for this run. It does not prove every possible input, access rule or failure condition.
Add a negative case that expects a failure:
import pytest
def test_rejects_a_non_text_title(tmp_path):
path = tmp_path / "chapters.json"
path.write_text('["Python and Roots", 8]', encoding="utf-8")
with pytest.raises(ValueError):
load_titles(path)
pytest.raises checks that the enclosed operation raises the expected exception. If no exception occurs, the test fails. Together, the tests challenge both acceptance and rejection. Add a missing-file case and malformed JSON case before relying on the reader in a solution.
Python can disable ordinary assert statements when started with optimisation options. That is another reason to use explicit validation and raise for required input checks, rather than making production validation depend on assert.
Safety floor
Run file-writing tests in a temporary folder or another explicitly approved location. Never try a destructive test against the only copy of useful data. A file reader exposed as a tool must not accept arbitrary caller-controlled paths merely because this local teaching function does.
The Python file tutorial, pathlib reference, pytest guide and expected-exception guide support the examples.
Check the chapter with the explanation closed
Give yourself two points for each answer: one for the correct outcome and one for the reason. Aim for eight out of ten, then revisit every missed explanation before continuing. These are this book's review questions, not an external certificate exam.
- A function prints a correct title but its caller receives
None. What is missing, and why? - A lookup returns “not found” after checking only the first title. Which placement would you inspect?
- An AI changes a list through a second name. Why might the original name now show changed contents?
- A response is valid JSON with a lesson count of
"seven". Which check is still missing? - A file reader passes the happy-path test but changes the file. What assertion exposes that defect, and where should that test run?
Open the review criteria after your attempt
- It needs a
returnthat supplies the result. Displaying text is a separate operation. - Inspect whether the missing-result
returnis inside the loop instead of after it. - Assignment can give two names to the same mutable object; it does not automatically copy it.
- A shape/type check is missing. JSON syntax does not establish the required numeric meaning.
- Compare the file contents before and after the read. Use a test-created temporary file, not important working data.
For a real application, specify a bounded file-reading requirement for The Bridge Balance or another authorised solution, then inspect its existing implementation and tests. A second application, such as HomeoAI, needs its own approved data and access rules; copying the example alone does not establish that work is complete.
The next chapter follows Python into classes, validated data and asynchronous work, then uses those pieces in MCP and LangChain. Bring your habit of predicting and checking with you; the frameworks will not replace it.