Files, JSON, and pathlib
Files, JSON, and pathlib
Most backend data arrives as text and has to become Python objects, and most of it leaves the same way. The standard library covers the common cases well. pathlib.Path represents a file path as an object with methods, so joining directories, checking existence, reading text, and listing a folder are method calls rather than string surgery. The json module converts between JSON text and the containers from lesson three. Together they are enough to give Relay a seed file of tickets and a knowledge base of help articles before there is a database.
The one thing to fix in your habits from the start is encoding. Reading a file without saying which encoding it is in uses the platform default, which is UTF-8 on most systems and not on Windows. Python 3.15 makes UTF-8 the default everywhere; until then, write encoding="utf-8" on every text read and write, and the same file works on every machine.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.