Python
Python Essentials for Data Engineers, Part 2
Write functions and modules, read and write CSV files with the standard library, validate records, log what happens and build a small batch job you can rerun safely.
On this page
In Part 1 you validated eight records typed directly into Python. Real pipelines read data from files, reject what is wrong without stopping, write results somewhere useful and can be run again tomorrow without making a mess. This lesson builds exactly that: a small batch job that reads sales_transactions.csv, validates every row, calculates a line total, writes valid and rejected rows to separate files and prints a summary. It uses only Python’s standard library.
It is the third Python lesson of Stage 2 of the Become a Data Engineer roadmap.
What you will learn
- Write functions with parameters and return values
- Import modules from the standard library and from your own files
- Build file paths with
pathlib - Read and write CSV files with the
csvmodule - Handle expected errors with
try/except - Validate records and keep the reasons for rejection
- Separate processing logic from file input and output
- Log what a script does with the
loggingmodule - Check your logic with
assert - Make a script safe to rerun
Before you start
- Prerequisites: Python Essentials for Data Engineers, Part 1, and the
sales-pipelinefolder from Lesson 1 withdata/sales_transactions.csvin place and the virtual environment active. - Estimated time: 90–120 minutes, including the exercises.
- Packages: none. Everything here is in the standard library.
Short examples go in a practice file, practice.py, in sales-pipeline: add each one below the previous one and run python practice.py from the project folder. The batch job at the end is made of three separate files that you will create when you get there.
Where this lesson is going
- Read CSVdata/sales_transactions.csv
- Validate each rowrequired fields, quantity, price
- validvalid_sales.csvwith line_total added
- invalidrejected_sales.csvwith the error reason
- summary.txtcounts and total revenue
Functions, parameters and return values
A function packages a piece of logic under a name so you can reuse it and test it. You define it with def, list its parameters in parentheses and send a result back with return:
def line_total(quantity, unit_price):
return quantity * unit_price
print(line_total(3, 4.50))
print(line_total(2, 39.00))
def is_valid_quantity(quantity):
return quantity > 0
print(is_valid_quantity(5), is_valid_quantity(0))
def describe_sale(transaction_id, quantity, unit_price, currency="EUR"):
total = line_total(quantity, unit_price)
return f"{transaction_id}: {total:.2f} {currency}"
print(describe_sale("T1001", 3, 4.50))
print(describe_sale("T1001", 3, 4.50, currency="USD"))13.5
78.0
True False
T1001: 13.50 EUR
T1001: 13.50 USD
- The values you pass in (
3,4.50) are called arguments; inside the function they are available under the parameter names. returnends the function and hands the value back. A function withoutreturnreturnsNone, a classic beginner surprise when the result is used later.currency="EUR"is a default value: callers can leave it out, or override it by name.- Functions can call other functions, as
describe_salecallsline_total. Small functions that do one thing are easy to read and easy to test.
Imports and modules
A module is a Python file. import makes its code available in yours. The standard library is a collection of modules that ship with Python:
import math
from pathlib import Path
print(math.ceil(4.2))
print(Path("data") / "sales_transactions.csv")5
data\sales_transactions.csv
On macOS and Linux the second line prints data/sales_transactions.csv: Path uses the right separator for your operating system. import math gives you the module and you write math.ceil; from pathlib import Path gives you one name directly. Put imports at the top of a file, standard-library modules first.
Your own files are modules too. A file named sales_rules.py in the same folder can be imported with from sales_rules import validate_record. You will do exactly that below.
File paths with pathlib
pathlib.Path represents a location on disk. The / operator joins path parts, and the path object can tell you about the file:
data_file = Path("data") / "sales_transactions.csv"
print(data_file.name)
print(data_file.suffix)
print(data_file.exists())sales_transactions.csv
.csv
True
A relative path such as data/sales_transactions.csv is resolved from the folder your terminal is in, not from the folder of the script. That is why you run the examples from sales-pipeline. The batch job below avoids the problem by building paths from the script’s own location.
Read a CSV file
The csv module’s DictReader turns each line of a CSV file into a dictionary whose keys are the header names, which is exactly the shape you used in Part 1:
import csv
with data_file.open(newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
rows = list(reader)
print(len(rows))
print(rows[0])
print(type(rows[0]["quantity"]))20
{'transaction_id': 'T1001', 'order_date': '2026-03-02', 'store': 'Lisbon', 'product': 'Notebook', 'quantity': '3', 'unit_price': '4.50'}
<class 'str'>
with … as file:opens the file and closes it automatically at the end of the block, even if an error happens.newline=""lets thecsvmodule handle line endings itself; the Python documentation recommends it for every CSV file.encoding="utf-8"avoids depending on your computer’s default.- Every value is a string, including
'3'and'4.50', and a missing value is an empty string'', notNone. Converting and validating text is the job of the next sections.
Handle expected errors with try and except
Converting text that is not a number raises an error. In Part 1 an error stopped the program; with try / except you decide what happens instead:
def to_int(text):
try:
return int(text)
except ValueError:
return None
print(to_int("3"))
print(to_int("two"))
print(to_int(""))3
None
None
Without the try, int("two") stops the program with ValueError: invalid literal for int() with base 10: 'two'. Catch only the error you expect (ValueError here), never everything: a bare except: also hides genuine bugs, such as a misspelled variable name.
Validate records
Validation rules deserve a file of their own. Create sales_rules.py in sales-pipeline:
"""Validation and transformation rules for sales transactions.
These functions never read or write files, so they are easy to test.
"""
REQUIRED_FIELDS = ["transaction_id", "order_date", "store", "product", "quantity", "unit_price"]
def parse_quantity(text):
"""Return the quantity as an int, or raise ValueError."""
quantity = int(text)
if quantity <= 0:
raise ValueError("quantity must be greater than zero")
return quantity
def parse_price(text):
"""Return the unit price as a float, or raise ValueError."""
price = float(text)
if price <= 0:
raise ValueError("unit_price must be greater than zero")
return price
def validate_record(record):
"""Return a list of problems with one raw record. An empty list means it is valid."""
problems = []
for field in REQUIRED_FIELDS:
value = record.get(field)
if value is None or value.strip() == "":
problems.append(f"missing {field}")
if problems:
return problems
try:
parse_quantity(record["quantity"])
except ValueError:
problems.append(f"invalid quantity: {record['quantity']}")
try:
parse_price(record["unit_price"])
except ValueError:
problems.append(f"invalid unit_price: {record['unit_price']}")
return problems
def transform_record(record):
"""Return a clean copy of a valid record with a calculated line_total."""
quantity = parse_quantity(record["quantity"])
unit_price = parse_price(record["unit_price"])
return {
"transaction_id": record["transaction_id"].strip(),
"order_date": record["order_date"].strip(),
"store": record["store"].strip(),
"product": record["product"].strip(),
"quantity": quantity,
"unit_price": f"{unit_price:.2f}",
"line_total": f"{quantity * unit_price:.2f}",
}
How it works:
- The text between triple quotes at the top of the file and of each function is a docstring: documentation that editors show when you hover over the name.
REQUIRED_FIELDSis a constant, written in capitals by convention, shared by every function.parse_quantityandparse_priceraise aValueErrorthemselves when a number parses but breaks a business rule (zero or negative). The caller handles “not a number” and “not positive” the same way.validate_recordreturns a list of problems rather thanTrueorFalse, so a rejected row can say why. It checks required fields first and returns early, so it never tries to convert a value that is missing.transform_recordassumes a valid record and builds a clean copy: it strips spaces, converts the numbers, formats prices with two decimals and adds the derived fieldline_total.
Now try the rules on five rows of the file, from practice.py:
from sales_rules import validate_record
for row in rows[4:9]:
print(row["transaction_id"], validate_record(row))T1005 ['invalid quantity: 0']
T1006 []
T1007 ['missing product']
T1008 ['invalid quantity: -1']
T1009 ['invalid quantity: two']
rows[4:9] is a slice: the items at positions 4 to 8. An empty list means the row is valid.
Write a CSV file
DictWriter is the mirror image of DictReader. You give it the column names, write the header once, then write rows:
output_file = Path("output") / "practice.csv"
output_file.parent.mkdir(exist_ok=True)
with output_file.open("w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["transaction_id", "line_total"])
writer.writeheader()
writer.writerow({"transaction_id": "T1001", "line_total": "13.50"})
print(output_file.read_text(encoding="utf-8").strip())transaction_id,line_total
T1001,13.50
Mode "w" creates the file, or replaces it if it already exists. Mode "a" (append) adds to the end instead; run an appending script twice and every row appears twice. For a batch job that must be safe to rerun, write complete output files with "w". mkdir(exist_ok=True) creates the folder only if it is missing.
Log what happens
print() is fine while learning, but scripts that run unattended should log: every message gets a level (DEBUG, INFO, WARNING, ERROR) and can later be sent to a file or a monitoring tool without changing the code:
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger("practice")
logger.info("Read %d rows", len(rows))
logger.warning("Rejected %s: %s", "T1005", "invalid quantity: 0")
logger.debug("This line is hidden at INFO level")INFO Read 20 rows
WARNING Rejected T1005: invalid quantity: 0
level=logging.INFO shows INFO and everything more serious, so the DEBUG line is hidden. The %d and %s placeholders are filled from the extra arguments. In production you would usually add the time to the format with %(asctime)s. Logging writes to the error stream, so in some terminals these lines appear in a different colour or order than print() output.
Separate processing logic from file I/O
Look again at sales_rules.py: it never opens a file. It receives dictionaries and returns lists and dictionaries. That separation is the most useful design habit in data engineering:
- the rules can be tested with a few hand-written records, in milliseconds, without any files;
- the I/O (reading and writing files) can change, for example from CSV to a database, without touching the rules;
- when a number looks wrong, you know which half to look in.
The batch job below is therefore two files: sales_rules.py decides, process_sales.py reads, writes and reports.
Build the batch job
Create process_sales.py in sales-pipeline:
"""Batch job: read sales_transactions.csv, validate, transform and write the results."""
import csv
import logging
from pathlib import Path
from sales_rules import REQUIRED_FIELDS, transform_record, validate_record
PROJECT_DIR = Path(__file__).parent
INPUT_FILE = PROJECT_DIR / "data" / "sales_transactions.csv"
OUTPUT_DIR = PROJECT_DIR / "output"
VALID_FILE = OUTPUT_DIR / "valid_sales.csv"
REJECTED_FILE = OUTPUT_DIR / "rejected_sales.csv"
SUMMARY_FILE = OUTPUT_DIR / "summary.txt"
VALID_COLUMNS = REQUIRED_FIELDS + ["line_total"]
REJECTED_COLUMNS = REQUIRED_FIELDS + ["error"]
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger("process_sales")
def read_records(path):
with path.open(newline="", encoding="utf-8") as file:
return list(csv.DictReader(file))
def write_records(path, columns, records):
# Mode "w" replaces the file, so running the job again never duplicates rows.
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=columns)
writer.writeheader()
writer.writerows(records)
def process(records):
valid, rejected = [], []
for record in records:
problems = validate_record(record)
if problems:
rejected.append({**record, "error": "; ".join(problems)})
else:
valid.append(transform_record(record))
return valid, rejected
def build_summary(records, valid, rejected):
revenue = sum(float(row["line_total"]) for row in valid)
units = sum(row["quantity"] for row in valid)
return {
"rows_read": len(records),
"valid_rows": len(valid),
"rejected_rows": len(rejected),
"units_sold": units,
"total_revenue": f"{revenue:.2f}",
}
def main():
if not INPUT_FILE.exists():
logger.error("Input file not found: %s", INPUT_FILE)
raise SystemExit(1)
records = read_records(INPUT_FILE)
logger.info("Read %d rows from %s", len(records), INPUT_FILE.name)
valid, rejected = process(records)
for row in rejected:
logger.warning("Rejected %s: %s", row["transaction_id"] or "(no id)", row["error"])
OUTPUT_DIR.mkdir(exist_ok=True)
write_records(VALID_FILE, VALID_COLUMNS, valid)
write_records(REJECTED_FILE, REJECTED_COLUMNS, rejected)
summary = build_summary(records, valid, rejected)
SUMMARY_FILE.write_text(
"".join(f"{key}: {value}\n" for key, value in summary.items()), encoding="utf-8"
)
logger.info("Summary: %s", summary)
if __name__ == "__main__":
main()
Read it from the bottom up:
if __name__ == "__main__":runsmain()only when the file is executed as a script, not when another file imports it. That keeps it importable, and testable, later.main()is the only function that reads and writes. It checks the input exists, reads, processes, logs each rejection, writes three outputs and logs a summary. If the input file is missing it logs anERRORand stops with exit code 1, the signal schedulers use to mark a job as failed.PROJECT_DIR = Path(__file__).parentis the folder that contains the script, so the job finds its files whatever folder you start it from.process()sends each record to the rules and collects two lists.{**record, "error": …}copies the original record and adds anerrorcolumn, so a rejected row keeps all its original values.build_summary()usessum()with a generator expression, a compact loop written inside the parentheses:sum(float(row["line_total"]) for row in valid)adds up every line total.
Run it
python process_sales.py
Expected output (exactly these lines, in this order):
INFO Read 20 rows from sales_transactions.csv
WARNING Rejected T1005: invalid quantity: 0
WARNING Rejected T1007: missing product
WARNING Rejected T1008: invalid quantity: -1
WARNING Rejected T1009: invalid quantity: two
WARNING Rejected T1011: missing unit_price
WARNING Rejected T1012: invalid unit_price: 24,90
WARNING Rejected (no id): missing transaction_id
WARNING Rejected T1018: invalid unit_price: -24.90
INFO Summary: {'rows_read': 20, 'valid_rows': 12, 'rejected_rows': 8, 'units_sold': 43, 'total_revenue': '479.70'}
The job creates three files in output. valid_sales.csv holds the 12 valid rows with the new line_total column:
transaction_id,order_date,store,product,quantity,unit_price,line_total
T1001,2026-03-02,Lisbon,Notebook,3,4.50,13.50
T1002,2026-03-02,Lisbon,Desk Lamp,1,24.90,24.90
T1003,2026-03-02,Porto,Backpack,2,39.00,78.00
T1004,2026-03-03,Porto,Notebook,5,4.50,22.50
T1006,2026-03-03,Faro,Desk Lamp,2,24.90,49.80
T1010,2026-03-05,Lisbon,Water Bottle,4,12.00,48.00
T1013,2026-03-06,Faro,Notebook,10,4.50,45.00
T1014,2026-03-06,Lisbon,Backpack,1,39.00,39.00
T1016,2026-03-07,Porto,Notebook,6,4.50,27.00
T1017,2026-03-07,Faro,Water Bottle,3,12.00,36.00
T1019,2026-03-08,Faro,Backpack,2,39.00,78.00
T1020,2026-03-08,Lisbon,Notebook,4,4.50,18.00
rejected_sales.csv keeps the 8 rejected rows exactly as they arrived, with the reason:
transaction_id,order_date,store,product,quantity,unit_price,error
T1005,2026-03-03,Lisbon,Water Bottle,0,12.00,invalid quantity: 0
T1007,2026-03-04,Faro,,1,15.00,missing product
T1008,2026-03-04,Porto,Backpack,-1,39.00,invalid quantity: -1
T1009,2026-03-04,Lisbon,Notebook,two,4.50,invalid quantity: two
T1011,2026-03-05,Faro,Backpack,1,,missing unit_price
T1012,2026-03-05,Porto,Desk Lamp,1,"24,90","invalid unit_price: 24,90"
,2026-03-06,Porto,Water Bottle,2,12.00,missing transaction_id
T1018,2026-03-07,Lisbon,Desk Lamp,2,-24.90,invalid unit_price: -24.90
Notice the quotes around "24,90": the csv module adds them because the value contains a comma, the column separator. That is why reading CSV with split(",") instead of the csv module breaks on real data.
summary.txt records the run:
rows_read: 20
valid_rows: 12
rejected_rows: 8
units_sold: 43
total_revenue: 479.70
Check the numbers: 12 valid plus 8 rejected is the 20 rows read, and nothing was lost. The first eight rows contribute the 188.70 you calculated in Part 1.
Rerun it safely
Run the job a second time. The console shows the same lines, and the three files are identical, not doubled, because every output is rewritten in full with mode "w". You can prove it by comparing file fingerprints before and after a rerun:
# Windows PowerShell
Get-FileHash output\valid_sales.csv, output\rejected_sales.csv, output\summary.txt
# macOS / Linux
shasum -a 256 output/valid_sales.csv output/rejected_sales.csv output/summary.txt
(On Linux, sha256sum with the same file names works too.) The fingerprints (hashes) are the same after every run. A job that produces the same result however many times it runs is called idempotent, and it is what lets you rerun a failed night’s load without cleaning up first. Production jobs go further, for example writing to a temporary file and renaming it so a crash never leaves a half-written output, but the principle is the same.
Test the rules with assertions
assert condition does nothing when the condition is true and stops with an AssertionError when it is false. A few assertions on hand-written records make a first, very fast test suite. Create check_sales_rules.py:
"""Small checks for sales_rules.py. Run: python check_sales_rules.py"""
from sales_rules import transform_record, validate_record
good = {
"transaction_id": "T1001",
"order_date": "2026-03-02",
"store": "Lisbon",
"product": "Notebook",
"quantity": "3",
"unit_price": "4.50",
}
assert validate_record(good) == []
assert transform_record(good)["line_total"] == "13.50"
assert validate_record({**good, "product": ""}) == ["missing product"]
assert validate_record({**good, "quantity": "0"}) == ["invalid quantity: 0"]
assert validate_record({**good, "quantity": "two"}) == ["invalid quantity: two"]
assert validate_record({**good, "unit_price": "24,90"}) == ["invalid unit_price: 24,90"]
print("All checks passed")
python check_sales_rules.py
All checks passed
Each check builds a variation of one good record with {**good, "field": value} and states the exact result expected. Break one on purpose, for example expect "13.5" instead of "13.50", and the script stops with a traceback ending in AssertionError, pointing at the failing line. These checks run without any input file, which is the payoff of keeping the rules free of I/O. Later in the roadmap you will move checks like these into pytest, a testing framework that reports every failure at once.
Exercises
Solutions follow the knowledge check.
-
Revenue per store. Write
store_revenue.pythat readsoutput/valid_sales.csvand prints the revenue of each store, sorted by store name. Expected output:Faro: 208.80 Lisbon: 143.40 Porto: 127.50The three values add up to 479.70.
-
More checks. Add three assertions to
check_sales_rules.py: a negative price, a blanktransaction_idand a blankunit_price. Expected output:All checks passed. -
A missing input. Temporarily rename
data/sales_transactions.csvand run the job. Expected: one line starting withERROR Input file not found:followed by the full path, and exit code1(check it with$LASTEXITCODEin PowerShell orecho $?in macOS/Linux shells). Rename the file back afterwards.
Common mistakes and troubleshooting
ValueError: invalid literal for int() with base 10: '4.50'.int()only accepts whole numbers written as text. Usefloat()for prices.ValueError: could not convert string to float: '24,90'. Python expects a dot as the decimal separator. Here, the rule rejects such values; converting them is a business decision, not a silent fix.FileNotFoundError: [Errno 2] No such file or directory. A relative path is resolved from the terminal’s current folder. Run fromsales-pipeline, or build paths fromPath(__file__).parentas the batch job does.ModuleNotFoundError: No module named 'sales_rules'. The rules file is missing, misnamed or in a different folder. It must besales_rules.py, next to the script that imports it.- Every row appears twice after a second run. The file was opened with
"a"(append). Use"w"for complete outputs. - Blank lines between rows in the CSV on Windows. The file was opened without
newline="". - A function result is
None. The function has noreturn, or returns from only one branch of anif. except:hides a real bug. Catch the specific error you expect, such asValueError.
Knowledge check
- What is the difference between a parameter and an argument?
- Why does
csv.DictReadergive you'3'and not3? - Why does
validate_recordreturn a list instead ofTrueorFalse? - What makes
process_sales.pysafe to run twice? - Why are the rules in
sales_rules.pyand not inprocess_sales.py? - What does
if __name__ == "__main__":do?
Answers
- A parameter is the name in the function definition (
quantity); an argument is the value passed when calling it (3). - A CSV file is text, and the
csvmodule does not guess types. Converting and validating is your code’s job. - So a rejected row can carry every reason it failed, which ends up in the
errorcolumn. - Every output file is written in full with mode
"w", so a rerun replaces the previous results instead of adding to them. - So the rules can be tested without files, and the file handling can change without touching the rules.
- It runs
main()only when the file is executed directly, not when another module imports it.
Exercise solutions
1. Revenue per store (store_revenue.py):
import csv
from pathlib import Path
revenue_by_store = {}
with (Path("output") / "valid_sales.csv").open(newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
store = row["store"]
revenue_by_store[store] = revenue_by_store.get(store, 0) + float(row["line_total"])
for store, revenue in sorted(revenue_by_store.items()):
print(f"{store}: {revenue:.2f}")
sorted() on the dictionary’s items sorts by key, the store name. The values in the file are text, so float() converts them before adding.
2. More checks. Add these lines before the final print:
assert validate_record({**good, "unit_price": "-24.90"}) == ["invalid unit_price: -24.90"]
assert validate_record({**good, "transaction_id": ""}) == ["missing transaction_id"]
assert validate_record({**good, "unit_price": ""}) == ["missing unit_price"]
3. A missing input. main() checks INPUT_FILE.exists() before reading, logs the full path so you know exactly where it looked, and raises SystemExit(1) instead of continuing with no data.
Next lesson
You have written a complete, if small, batch job: read, validate, transform, write, summarise and rerun safely, using only the standard library. The next lesson in Stage 2, Reading CSV Files with pandas, loads data with pandas, the library installed in Lesson 1, which handles larger files and many of these steps in fewer lines. Knowing what happens underneath will help you check that pandas did what you expected.
Was this helpful?
What could be better?
Thanks — that helps me improve Javi Builds.
Continue learning
- Cheat sheetRead and Write CSV, Parquet and JSONRead and write CSV, Parquet, and JSON with pandas while controlling schema, dates, nulls, compression, encoding, and production-safe file behavior.Open cheat sheet
- ArticleSet Up Python for Data EngineeringInstall Python on Windows, macOS or Linux, set up VS Code, create a virtual environment, install packages with python -m pip and run your first data script.Read article
What should I build next?
I'm building Javi Builds around practical problems data engineers actually face. Tell me what you'd like to see next.
Stay in the loop
Get the Javi Builds updates you actually care about.
Check your inbox
I sent you a confirmation link. Your subscription will be active after you confirm it.