Python Foundations·Structure your code

Files and errors

Read real data safely and handle failures without crashing.

Beginner 14 min read Lesson 8 of 480 Challenge included
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.

files.pyPython
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

Count the lines

Medium

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 here
Check 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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Strings and formatting
Lesson 8 of 480 · 0% of course