Reading and Writing Files · practice
Read Text Safely
A path answers “which file?” The next questions are “what kind of access?” and “how should these bytes become text?”
Here is the complete boundary this lesson builds:
with open(path, "r", encoding="utf-8") as handle:
# read from handle here
Read that first line from the inside out:
pathis the file to open;"r"means read mode;encoding="utf-8"says how stored bytes become Python; as handlegives the open file a temporary name.
Why with owns the handle
An open file is an operating-system resource. It should be closed when the work is finished, including when reading fails halfway through.
The with statement makes that lifetime visible. Python opens the file before entering the indented block and closes it when the block ends. It also closes the file when an handle.close() that a new
This is a context manager: the open(...) knows how to enter and leave a managed block safely. You will meet other context managers later. For now, the durable rule is small: when a file handle belongs to one operation, put that operation inside with.
Read lines without keeping empty records
data/books.txt contains one title per line and one deliberate blank line. Iterating over the handle gives you each line as text, including its final newline. .strip() removes that surrounding whitespace. An empty result should not become an empty book title.
Build the result with the
books = []
for line in handle:
title = line.strip()
if title:
books.append(title)
Use the path BOOKS_PATH. It is tempting to reach for the constant you can see at the top of the file, but a
Encoding is part of the file contract
UTF-8 can represent the non-ASCII title Cien años de soledad and ordinary English text in one portable encoding. Relying on a machine default leaves the same bytes open to different interpretations on different computers.
encoding="utf-8" is not error recovery. It is an explicit agreement. If a file’s bytes are not valid UTF-8, Python will raise UnicodeDecodeError; the next lesson decides where that expected boundary failure belongs.
Complete read_books(path) in the project editor, then submit.
If you get stuck on the loop, ask Monty what line.strip() returns for a line that contains only a newline. That single value explains why the blank line needs handling at all.
What does the with statement give you that a plain open does not?
Why pass encoding="utf-8" rather than relying on the default?
Task
Implement read_books(path).
Open the supplied
pathin explicit read mode with UTF-8 encoding.Manage the open handle with a
withstatement.Return a
of stripped, nonblank lines in their original order. Use the
; do not hard-code BOOKS_PATHor the seeded titles.
Leave the other