Match two CSV files with Python
Match orders to product names by SKU and verify the merged output.
Prepare two small files
Save these as products.csv and orders.csv in the same directory. Each SKU appears once in the product list. More than one order may reference the same SKU.
sku,product_name
A12,Notebook
B07,Pensku,quantity
A12,2
B07,4
A12,1
Check the headers and match the rows
Save the Python example as match_csv.py. The script validates the headers and product keys before printing the merged CSV. It reports an order with an unknown SKU so you can review the input.
import csv
import sys
def read_rows(filename, headers):
with open(filename, "r", encoding="utf-8-sig", newline="") as source:
reader = csv.DictReader(source, strict=True)
if reader.fieldnames != headers:
raise ValueError(f"{filename}: expected header {','.join(headers)} required.")
for row in reader:
location = f"{filename} line {reader.line_num}"
if None in row:
raise ValueError(f"{location}: extra column.")
sku = (row[headers[0]] or "").strip()
value = (row[headers[1]] or "").strip()
if not sku or not value:
raise ValueError(f"{location}: empty or missing field.")
yield sku, value, location
try:
products = {}
for sku, name, location in read_rows(
"products.csv", ["sku", "product_name"]
):
if sku in products:
raise ValueError(f"{location}: duplicate SKU {sku}.")
products[sku] = name
result = []
for sku, quantity, location in read_rows(
"orders.csv", ["sku", "quantity"]
):
if sku not in products:
raise ValueError(f"{location}: {sku} is missing from the product list.")
result.append((sku, products[sku], quantity))
except (OSError, ValueError, csv.Error) as error:
raise SystemExit(str(error)) from None
writer = csv.writer(sys.stdout, lineterminator="\n")
writer.writerow(("sku", "product_name", "quantity"))
writer.writerows(result)
Try both valid and invalid input
Run the script and compare its output with the expected rows. Then add a duplicate to the product list or remove a header and check that the script reports the problem.
python3 match_csv.pysku,product_name,quantity
A12,Notebook,2
B07,Pen,4
A12,Notebook,1