01.06 Lesson 6 of 10
42 minFiles, CSV & Errors
Read and write files safely, work with paths and handle predictable failures.
By the end of this lesson
You will be able to
- Use
pathlibfor file paths. - Use a context manager to open files.
- Read structured CSV data.
- Catch specific exceptions and report useful errors.
Build paths from the project location
Avoid hard-coded machine-specific absolute paths. Use pathlib.Path to construct paths relative to the project and check whether expected files exist before reading them.
from pathlib import Path
PROJECT_DIR = Path(__file__).resolve().parent
DATA_DIR = PROJECT_DIR / "data"
CSV_PATH = DATA_DIR / "hour.csv"
if not CSV_PATH.exists():
raise FileNotFoundError(f"Dataset not found: {CSV_PATH}") Let the file close reliably
The with statement manages the file lifecycle. When reading CSV manually, use the standard csv module; when the next lessons begin, pandas will handle tabular loading more directly.
import csv
with CSV_PATH.open(newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
first_row = next(reader)
print(first_row) Catch only errors you can handle
Catch the specific exception you expect, add context and either recover or stop. Avoid except Exception: pass; it hides the cause and can make a bad report look successful.
try:
hour = int("not-an-hour")
except ValueError as error:
print(f"Invalid hour value: {error}") Apply what you learned
ExerciseCreate a reliable dataset loader
Write a loader that reports clear errors for a missing or unreadable CSV file.
- Accept a path as a function argument.
- Check that the path exists and is a file.
- Open the file using a context manager.
- Catch file and parsing errors at the user-facing boundary.
- Return parsed rows or raise a clear, specific error.
A missing path and a malformed file produce understandable messages; a valid file loads successfully.
Free references
Study resources
- 01
- 02
- 03 Try/Except Blocks for Error Handling Video
Watch for the control flow of
try,except,elseandfinally.
Check your understanding
Self-test
-
Question 1
Why is
Path(__file__).resolve().parentuseful?It anchors a path to the location of the current source file instead of relying on the terminal’s current working directory. -
Question 2
Why should exceptions be specific?
A specific handler documents the expected failure and avoids swallowing unrelated programming errors.
Completion check
Move on when
The loader handles paths, closes files reliably and reports expected failures clearly.