Loading WURK...
RomanMotion
RomanMotion
Product ad & launch videos · 3D product visuals · app & AI builder. Concept to final cut in days. Open for projects.

Clean a messy CSV with your coding agent: a script you can rerun, not a chat paste

Turn a messy CSV into a repeatable cleanup job with clear rules, a row-count report, and a separate file for rejects.

Published on November 11, 20267 min read

You pasted a spreadsheet into a chat and asked for clean rows back. Now you’re wondering whether a row disappeared or a customer ID changed along the way. A small script gives you rules you can inspect, a report you can check, and a way to clean the next file without starting over.

Ask your coding agent to inspect the CSV first, then write a Python script for the cleanup rules you approve. Keep the original file, put accepted rows in a new file, and send anything the script can’t safely handle to a separate rejects file. Check the totals and sample the results before using them.

Look at the file before cleaning it

A pasted chat response can look tidy while leaving you with no dependable record of which values changed. It may also omit rows, and copying the result back into a spreadsheet gives you another chance to miss something.

Start with a profile instead. Ask your coding agent to read the file without changing it and report:

  • The number of data records and the column names
  • Blank values in each column
  • Repeated values in the proposed unique key
  • Dates that are blank, invalid, or use unexpected formats
  • The file encoding and delimiter, if known

A key is the field you expect to identify a record, such as id. Don’t assume it is unique just because it has that name. If the same customer can have several orders, deduplicating on customer ID could reject legitimate orders.

Keep sensitive data out of a chat unless you’re comfortable sharing it there. Your agent can work with a local file and report counts rather than paste every row into its response.

The profile helps you make decisions before the agent writes code. Any agent that can read files and run Python on your machine can do this step; if you don't have one set up yet, you can try the zcode agent harness free. For example: should a blank date be rejected, left blank, or filled from another field? The script should follow your answer, not make one up.

Give your agent rules it can check

Once you understand the columns, paste this instruction and replace the bracketed details:

Inspect [input file] without changing it. Report the row count,
column names, blanks, duplicate values in [key], and dates that
do not match [expected date format].

Then write a Python script that:
- Keeps the original input file unchanged.
- Trims surrounding whitespace from each field.
- Reads IDs as strings so leading zeros are preserved.
- Converts valid dates from [input format] to YYYY-MM-DD.
- Rejects missing keys and invalid or missing dates.
- Keeps the first valid row for each [key]; reject later ones.
- Writes accepted rows to clean.csv.
- Writes rejected rows to rejects.csv with their original
  fields, record number, and a reason.
- Stops on CSV parsing errors rather than silently skipping data.
- Prints input, clean, and rejected row counts.

Check that input rows equal clean rows plus rejected rows.
Test with sample rows covering valid data, duplicates,
blank keys, invalid dates, and unexpected column counts.
Show me the script, commands, and test results.
Do not overwrite the original input.

Adjust the duplicate rule to fit your data. Keeping the first valid row is predictable, but it may not be the right choice if later rows contain corrections. Ask the agent to flag conflicting records for review if you can’t choose safely.

A small script you can adapt

This example uses Python’s built-in csv module, so it doesn’t need a separate package. It expects a comma-separated file named input.csv with unique headers including id and date. Other columns are carried through.

Dates must be year-month-day or day/month/year. A missing ID, invalid date, duplicate ID, or wrong number of fields sends the original record to rejects.csv. The first valid record for an ID is kept.

I ran it on a small test file with a padded name, a day/month/year date, a duplicate ID, a blank ID, a 30 February and a row with an extra field. It printed Input: 7 | Clean: 3 | Rejected: 4, kept 001 with its leading zero, and each reject carried the right reason.

Save this as clean.py:

import csv
import json
from datetime import datetime

# Use ";" for semicolon-separated input.
with open("input.csv", encoding="utf-8-sig", newline="") as f:
    reader = csv.reader(f, delimiter=",", strict=True)
    header = next(reader)
    if len(set(header)) != len(header) or not {"id", "date"} <= set(header):
        raise ValueError("Need unique headers including id and date")
    rows = list(reader)  # Stop on a CSV parsing error before writing.

clean, rejects, seen = [], [], set()

for number, original in enumerate(rows, start=1):
    reason = ""

    if len(original) != len(header):
        reason = "wrong number of fields"
    else:
        row = dict(zip(header, (value.strip() for value in original)))
        if not row["id"]:
            reason = "missing id"
        else:
            parsed = None
            for fmt in ("%Y-%m-%d", "%d/%m/%Y"):
                try:
                    parsed = datetime.strptime(row["date"], fmt).date()
                    break
                except ValueError:
                    pass

            if parsed is None:
                reason = "invalid date"
            elif row["id"] in seen:
                reason = "duplicate id"
            else:
                row["date"] = parsed.isoformat()
                seen.add(row["id"])
                clean.append(row)

    if reason:
        rejects.append([
            number, reason, json.dumps(original, ensure_ascii=False)
        ])

assert len(rows) == len(clean) + len(rejects)

with open("clean.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writeheader()
    writer.writerows(clean)

with open("rejects.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["record", "reason", "original_fields_json"])
    writer.writerows(rejects)

print(f"Input: {len(rows)} | Clean: {len(clean)} | Rejected: {len(rejects)}")

Put input.csv beside the script and run:

python3 clean.py

The script leaves input.csv alone, but overwrites existing clean.csv and rejects.csv files in that folder. Move or rename any outputs you want to keep before running it again.

Check the results, not just the totals

The printed report should satisfy:

input records = clean records + rejected records

That check catches a mismatch in the script’s accounting; it doesn’t prove every accepted value is correct. Open both outputs. Compare a few accepted rows against the original, including IDs with leading zeros and dates near month boundaries. Read the rejection reasons and decide whether those records need correction.

In rejects.csv, record is the data-record position after the header, not necessarily the physical line number. The original fields are stored as a JSON list so even a record with extra fields can be reviewed.

The script stops if the CSV parser encounters a parsing error. Fix the source or ask your agent to handle that file safely; don’t assume partial output is complete. The Python csv documentation explains delimiter and quoting behavior.

If your agent uses pandas instead, its read_csv documentation covers string types, delimiters, encoding, and blank-line handling. Its to_datetime documentation explains explicit date formats and invalid-date handling. Specify the input format rather than guessing ambiguous dates.

Watch the format details

A UTF-8 file may start with a byte order mark, or BOM. The example reads with utf-8-sig, which handles that signature; Python documents that encoding in its codecs reference.

Some exports use semicolons instead of commas. If that’s your file, change the reader’s delimiter to ";" before running. Inspect the header and a few parsed records to make sure the separator is right. The example writes comma-separated outputs.

Treat IDs as text. Python’s CSV reader returns strings by default, as its documentation notes, so an ID such as 001 stays 001. If a spreadsheet already removed the zeros before export, the script cannot know how many to restore.

Finally, trimming whitespace is a rule, not an automatic improvement. If spaces at the edges of a field carry meaning in your data, narrow the cleanup to the columns where trimming is safe.

When the next export arrives, you rerun the script instead of starting a new chat, and the agent only gets involved if the rules need to change. If you do keep an agent busy with data jobs like this every week, this link gets you 10% off GLM coding plans.

Checklist before you use the cleaned file

  • The original input is backed up and unchanged
  • The profile shows columns, blanks, duplicates, and odd dates
  • The key and date format match the real data
  • The duplicate rule is appropriate for this file
  • Input records equal clean records plus rejected records
  • I reviewed rejected rows and sampled accepted rows
  • IDs, delimiter, encoding, and important whitespace are intact
  • I saved the script and its rules for the next file

We share more of these working notes on our blog.

If this saved you an afternoon, a small tip on this post helps keep these guides coming.

Conversation

Join the conversation

Share your thoughts with the author and other readers.

Comments0

Checking your account…

Latest comments

0
No comments yet. Be the first to share your thoughts.