Module 1 · Python Foundations for Security Data · Lesson 2 of 9
Parse CSV the safe way
Read a login export with csv.DictReader, validate every row, and count valid and rejected records separately.
In this lesson · about 22 minutes
- Open files safely with encoding and newline settings
- Read CSV rows by column name
- Reject incomplete rows without crashing, and count them
The synthetic file cyber-login.csv has four columns: timestamp,user,source_ip,outcome. Like real exports, it has problems: a missing user, a bad date, a time with no time zone, inconsistent capitals, and a name containing a comma.
Why not split on commas?
CSV allows quoting: "smith, j" is one field that contains a comma. line.split(",") cuts it in two and every column after it shifts. The csv module understands quoting, embedded commas and other formatting rules.
The safe pattern
import csv
with open("cyber-login.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["user"])
with open(...)closes the file reliably, even after an error.encoding="utf-8"avoids surprises on different systems;newline=""is what the csv module expects.DictReadergives each row as a dict keyed by the header, sorow["user"]still works if columns are reordered.- Never assume the current directory is where your script lives. In real scripts, build paths with
pathlib.
See the difference
Run it. Look at the row for smith, j in both outputs.
Exercise
Practice challenge 01: valid and rejected rows
Write count_records(path) that reads the CSV with csv.DictReader and returns a tuple (valid, rejected). A row is valid when all four fields (timestamp, user, source_ip, outcome) are present and not blank after stripping spaces.
Check your understanding0 of 2 correct
Quiz score: 0 of 2
Exercises solved: 0 of 1
Noviq Academy is free and for learning. All data in this course is synthetic and uses documentation IP ranges. Never paste real authentication logs or credentials into online tools. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.