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_textsees 301 lines. Line 2 starts withC0001. A path that does not exist must printmissing, not a traceback you ignore.
What you will learn
By the end of this lesson you will be able to:
- Read the customer file as text with
pathlib.Path. - Count lines and print the first customer id from line 2.
- Catch
FileNotFoundErrorfor a bad path. - Write a one-line card to a temp file and read it back.
- Import a module (
pandas) instead of pasting 300 rows into the script. - 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
C0001301 = 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:
missingCatch 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 SilverStep 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:
300len(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_csvturns 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_idIndependent 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
300Common 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.csvvscustomers.csv) and nobody caught it.Correction:
try/except FileNotFoundErrorand 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.