Rana Maninder Singh
Lesson 9 of 9Python basics

Files & exceptions

Lesson opener

In one line: Read a file with pathlib, count its lines (301 = header + 300 customers), and catch FileNotFoundError when the path is wrong — do not let a missing file crash the whole job.

Why it matters: pandas hid the file. Production scripts open paths, fail on a typo, and must say what was missing. try / except is that sentence. A module (import pandas) is how you reuse someone else's file-reading code.

Before this lesson: Data structures. Same data/customers.csv.

Practitioner focus: Path("data/customers.csv").read_text sees 301 lines. Line 2 starts with C0001. A path that does not exist must print missing, not a traceback you ignore.

What you will learn

By the end of this lesson you will be able to:

  1. Read the customer file as text with pathlib.Path.
  2. Count lines and print the first customer id from line 2.
  3. Catch FileNotFoundError for a bad path.
  4. Write a one-line card to a temp file and read it back.
  5. Import a module (pandas) instead of pasting 300 rows into the script.
  6. Explain why a bare except: is the wrong catch.

Worked example: the file is just text

Step 1 — Read and count. pandas is one module. Path.read_text is another way to see the same bytes.

from pathlib import Path

text = Path("data/customers.csv").read_text(encoding="utf-8")
lines = text.splitlines()
print(len(lines))
print(lines[1].split(",")[0])

Expected output:

301
C0001

301 = 1 header + 300 data rows. If you see 300, you dropped the header or a trailing row.

Step 2 — Missing path. Name the error. The job can continue.

from pathlib import Path

try:
    Path("data/missing-customers.csv").read_text(encoding="utf-8")
except FileNotFoundError:
    print("missing")

Expected output:

missing

Catch this error, not everything. A bare except: would also swallow a UnicodeDecodeError and hide a real encoding bug.

Step 3 — Write, then read. Use the system temp folder so the lesson does not drop a file into the repo.

from pathlib import Path
import tempfile

path = Path(tempfile.gettempdir()) / "py9_card.txt"
path.write_text("C0001 is Silver", encoding="utf-8")
print(path.read_text(encoding="utf-8"))

Expected output:

C0001 is Silver

Step 4 — A module is an import. You already used this every lesson. The point: import pandas as pd loads a file of functions someone else maintains. Your script stays short.

import pandas as pd

df = pd.read_csv("data/customers.csv")
print(len(df))

Expected output:

300

len(df) is 300 rows. len(lines) in Step 1 was 301 because it counted the header. Both are the same file.

Pause and think

Q1. Why 301 vs 300?

Text lines include the header. pandas read_csv turns the header into column names, not a row.

Q2. Why not except Exception: around every read?

You will hide bugs that are not "file missing" — bad encoding, permission, a typo in your own code.

Q3. Where should a scratch file go?

Temp, or an outputs/ folder you gitignore. Not next to the lesson markdown.

Guided practice: header line

Print only the first comma-separated field of line 1 (the header) — it should be customer_id.

from pathlib import Path

lines = Path("data/customers.csv").read_text(encoding="utf-8").splitlines()
print(lines[0].split(",")[0])

Expected output:

customer_id

Independent practice: catch the bad path and then load

Deliverable: print missing, then print 300 from pandas on the real file.

from pathlib import Path
import pandas as pd

try:
    Path("data/missing-customers.csv").read_text(encoding="utf-8")
except FileNotFoundError:
    print("missing")
df = pd.read_csv("data/customers.csv")
print(len(df))

Expected output:

missing
300

Common mistake

The deliberate mistake

Symptom: the script dies with a long traceback on a coworker laptop, and the last line is FileNotFoundError.

Diagnosis: the path was typed (customer.csv vs customers.csv) and nobody caught it.

Correction: try / except FileNotFoundError and print the path you tried.

Prevention: print Path("data/customers.csv").exists() once at the top of a new machine's first run.

Where this connects

What you can now do:

  • Read and write text with pathlib.
  • Catch a missing file by name.
  • See why pandas row count and text line count differ by one.

Next lesson: Functions in Python — the start of Python Advanced. You will wrap these reads in functions so the same load is not pasted into every script.