7 stages2 sections22 units

01.06 Lesson 6 of 10

42 min

Files, 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 pathlib for 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

Exercise

Create a reliable dataset loader

Write a loader that reports clear errors for a missing or unreadable CSV file.

  1. Accept a path as a function argument.
  2. Check that the path exists and is a file.
  3. Open the file using a context manager.
  4. Catch file and parsing errors at the user-facing boundary.
  5. Return parsed rows or raise a clear, specific error.
Done when

A missing path and a malformed file produce understandable messages; a valid file loads successfully.

Free references

Study resources

3 links
  1. 01
    Reading and writing files Article

    Read the with statement and text-file examples.

  2. 02
    Errors and exceptions Article

    Focus on handling exceptions and raising your own errors.

  3. 03
    Try/Except Blocks for Error Handling Video

    Watch for the control flow of try, except, else and finally.

Check your understanding

Self-test

2 questions
  1. Question 1

    Why is Path(__file__).resolve().parent useful?

  2. Question 2

    Why should exceptions be specific?

Completion check

Move on when

The loader handles paths, closes files reliably and reports expected failures clearly.

Quick find

Search Michi

Type to search every stage, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels