Files and errors
Read real data safely and handle failures without crashing.
What you will be able to do
- Open files with a context manager
- Catch specific exceptions
- Write a small automation script
Real programs deal with files and failure. A context manager closes the file even when an error occurs. Catch only the exceptions you can handle.
from pathlib import Path
path = Path("scores.csv")
try:
with path.open(encoding="utf-8") as file:
rows = [line.strip().split(",") for line in file if line.strip()]
except FileNotFoundError:
print("No scores file found — starting empty.")
rows = []
print(f"Loaded {len(rows)} rows")Your turn
MediumCount the lines
Read notes.txt and print how many non-empty lines it contains. Handle the missing-file case.
PYTHON · starter
from pathlib import Path
# your code hereCheck your understanding before moving on.
Knowledge checkQuestion 1
Why use a with statement to open a file?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.