Reading text files safely
A context manager closes a file resource predictably, including when work inside the block fails.
Learning objectives
- Open a text file for reading with a
withstatement. - Recognize that file operations can fail and need handling.
Use a context manager
PYTHON
with open("notes.txt", "r", encoding="utf-8") as file:
text = file.read()
print(text)open returns a file object. The with statement establishes a context that closes it when the indented block ends. Specifying UTF-8 makes the expected text encoding clear.
Failure modes and practice
The path may not exist, permissions may deny access, or the bytes may not match the chosen encoding. Programs that interact with real files should decide which exceptions to catch and what a user should see instead of silently losing an error.
Common mistakes and references
- Do not overwrite a file by using write mode when your intent is to read.
- Do not assume a relative path means the same thing in every execution environment.