
π This article includes 3 downloadable practice files β
In this article
Real files contain blanks, typos and impossible dates. The sales file in this course has two: a missing quantity and the date 31-06-2026 (June has 30 days). A good script skips such rows, says exactly which ones, and finishes the job.
good, bad = [], []
for line_no, r in enumerate(csv.DictReader(open("sales.csv")), start=2):
try:
r["qty"] = int(r["qty"])
r["date"] = dt.date.fromisoformat(r["date"])
good.append(r)
except ValueError as e:
bad.append(line_no)
log.warning("line %d skipped (%s): %s", line_no, r["invoice"], e)
Catch the specific exception you expect (ValueError, KeyError, FileNotFoundError). A bare except: also hides your own bugs.
logging instead of print
import logging
logging.basicConfig(filename="report.log", level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("sales")
log.info("loaded %d rows", len(good))
Levels (DEBUG, INFO, WARNING, ERROR) let you see details while testing and only problems in production. A log file is what tells you, next Monday, why the 6 a.m. scheduled run produced a short report.
finally: runs whether or not an error happened: close connections, delete temp files. With files, with open(...) as f: does this for you.Common mistakes
- Silently skipping rows with
except: pass. Always count and log what you skipped. - try around the whole script: keep try blocks small, around the line that can fail.
Practice
Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.
π Practice files for this article
β¬ Download all 3 files (ZIP Β· 4 KB)
- πLesson 3 scriptThe complete script from this lesson, ready to run.β¬ PY Β· 1 KB
- πExpected outputWhat the script printed when we ran it, to compare with yours.β¬ TXT Β· 263 B
- ποΈPractice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.β¬ ZIP Β· 4 KB
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.