Text Files and Exceptions
Read a text file and report an expected problem without hiding it.
python, files, text, exceptions, encodingRead a saved note
A file is a named place to store data beyond one run of a program. Imagine a
file named notes.txt in the program's current working directory containing
one line: Read every day. A path tells Python which file to open.
Relative paths are resolved from the current working directory, which is not
necessarily the folder containing the program.
open(..., "r", encoding="utf-8") opens text for reading using UTF-8.
with closes the file when its block ends, even if the block raises an
exception. Only open files you are authorised to access.
Python illustration
try:
with open("notes.txt", "r", encoding="utf-8") as file:
note = file.read()
print(note.strip())
except FileNotFoundError:
print("Could not find notes.txt.")
Prepared output when notes.txt contains Read every day. followed by a
newline — not live execution:
Read every day.
read() returns text and strip() removes leading and trailing whitespace
from the returned string, not from the file. If the file is absent, this
example instead reports Could not find notes.txt..
See the reasoning
Follow the example one step at a time
Compare the two paths in the lesson's file-reading example. This is a prepared teaching demonstration, not live code execution.
Case A: file exists
notes.txt: "Read every day.\n" try → open for reading
First consider a UTF-8 file containing the lesson's example line.
Understand exceptions
An exception reports that an operation could not proceed normally.
try runs a block; except FileNotFoundError handles that specific missing
file problem. Other problems, such as a permissions error or invalid UTF-8,
are not caught here and remain visible. Read the message rather than assuming
the program succeeded.
To create a new practice file without overwriting an existing one, use "x":
with open("practice-note.txt", "x", encoding="utf-8") as file:
file.write("Read every day.\n")
This example has no printed output. It raises FileExistsError if the file
already exists, rather than replacing it. By contrast, "w" can overwrite an
existing file and "a" appends to it. Run file-writing code only in a safe
location where you have permission. More exception tools and formats are
planned later.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
