PythonBeginner · Windows, macOS, or Linux with Python 3.12+

Find rows missing required CSV values

List data-record numbers and required fields that are empty or whitespace-only.

Before you begin

  • Python 3.12 or newer
What this script changesReads source data without editing it. Creates a new destination and refuses overwrite. Rows are held in memory. Spreadsheet formulas in cell text are preserved as text in the CSV; inspect untrusted data before opening in a spreadsheet.

Set up your example

  1. Save the complete code as csv-validate-required.py in a working folder.
  2. Save the provided sample files in that same folder; run commands from that folder.

Sample files in this download:

  • sample.csv
  • lookup.csv
  • second.csv
  • wide.csv
  • numbers.csv
  • sample.tsv

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is csv-validate-required.py.

Run the script

Run command
python "csv-validate-required.py" --input "sample.csv" --required "name,amount" --output "missing.csv"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

List data-record numbers and required fields that are empty or whitespace-only. Record 3 is flagged because amount is empty.

The complete script

csv-validate-required.py
#!/usr/bin/env python3
'Find rows missing required CSV values'
import argparse
import json
from pathlib import Path

def write_json(path, value):
    data = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    with Path(path).open("x", encoding="utf-8", newline="") as handle:
        handle.write(data)

import csv
import random
from collections import Counter, defaultdict
from decimal import Decimal
from datetime import datetime

def read_csv(path, delimiter=","):
    with Path(path).open(encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle, delimiter=delimiter)
        fields = reader.fieldnames
        if not fields or any(not f for f in fields) or len(set(fields)) != len(fields):
            raise ValueError("Use a nonempty, unique header for every column.")
        rows = list(reader)
    if any(None in row or None in row.values() for row in rows):
        raise ValueError("Every row must have exactly the header's number of cells.")
    return fields, rows

def require(fields, names):
    missing = set(names) - set(fields)
    if missing:
        raise ValueError("Missing columns: " + ", ".join(sorted(missing)))

def write_csv(path, fields, rows):
    with Path(path).open("x", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)

def number(value):
    result = Decimal(value or "0")
    if not result.is_finite():
        raise ValueError("Numbers must be finite.")
    return result

def main():
    parser = argparse.ArgumentParser(description='Find rows missing required CSV values')
    parser.add_argument("--input", required=True, help="CSV input with a header")
    parser.add_argument("--output", required=True, help="New destination file or directory")
    parser.add_argument("--required", required=True)
    args = parser.parse_args()
    fields, rows = read_csv(args.input)
    required = args.required.split(",")
    require(fields, required)
    result_fields = ["record", "missing_fields"]
    result = [{"record":i, "missing_fields":",".join(k for k in required if not row[k].strip())} for i,row in enumerate(rows,1) if any(not row[k].strip() for k in required)]
    write_csv(args.output, result_fields, result)

if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError, TypeError, ArithmeticError, IndexError, LookupError) as exc:
        raise SystemExit(str(exc))

Open source as plain text · Download source and sample files

How it works

  1. read_csv checks unique headers and row widths before processing.
  2. Record numbers count data rows from one; they are not physical line numbers when quoted cells span lines.
  3. Record 3 is flagged because amount is empty.

Make it your own

--required

Add date to --required to check it alongside name and amount.

Adapt the processing

Edit the missing-value predicate to also recognize explicit markers such as NULL.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

An output record number differs from a text editor line.

The number refers to parsed data records, excluding the header and multiline-cell line breaks.

The destination already exists.

Choose a new --output path. The script deliberately refuses to replace an existing result.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.