CSV files often arrive with extra spaces, inconsistent email casing, and duplicate contacts. This small Python project turns those rules into a repeatable command: read a contact file, normalize the usable rows, and write a separate result without overwriting the original.
The goal is deliberately narrow. We will accept exactly two columns, name and email, keep the first usable row for each email, and report how many rows were skipped. A clear rule is easier to test than a vague promise to “clean any CSV.”
Use Python 3.10 or later and a text editor. The project uses only the standard library. It is intended for small contact files that fit comfortably in memory. Use sample data while learning; do not upload private contact lists to a public demo.
Table of Contents
Define the rules before writing code
- The header must be exactly
name,emailin that order. - Trim and collapse whitespace in a person’s name.
- Trim the email and normalize its case for this exercise.
- Skip missing names, malformed addresses, extra columns, and incomplete rows.
- Keep the first valid row when an email appears more than once.
- Refuse to overwrite an existing output file or use the input path as the output.
Email case handling is a business rule, not a universal truth. This example treats addresses as case-insensitive contact identifiers. A system with stricter address semantics should adapt that rule. The regular expression is a basic format check; it does not prove an inbox exists or implement every valid email address form.
1. Create a sample input file
Save this as contacts.csv. The spaces around Ada’s name and the uppercase address are intentional. One later row repeats the same address. Two rows contain unusable email values.
name,email
Ada Santos ,ADA@example.com
Ada duplicate,ada@example.com
Ben Cruz,ben@example.com
Missing email,
Bad address,not-an-email
CSV is a format with quoting rules. A value containing a comma belongs inside double quotes. Do not split every input line with line.split(','); that breaks quoted names and multiline fields. Python’s CSV reader handles those structures for you.
2. Implement the cleaner
Save the following program as clean_csv.py. The data transformation is a function that accepts an open file, which also lets a test supply an in-memory string. The command-line wrapper handles paths, file errors, and the final summary.
"""Clean a small contact CSV without overwriting an existing file."""
import argparse
import csv
import re
from pathlib import Path
def clean_rows(source):
reader = csv.DictReader(source)
if reader.fieldnames != ["name", "email"]:
raise ValueError("Expected exactly these headers: name,email")
seen = set()
cleaned = []
skipped = 0
for row in reader:
if None in row or any(value is None for value in row.values()):
skipped += 1
continue
name = " ".join(row["name"].split())
email = row["email"].strip().casefold()
if not name or not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
skipped += 1
continue
if email in seen:
skipped += 1
continue
seen.add(email)
cleaned.append({"name": name, "email": email})
return cleaned, skipped
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
if args.input.resolve() == args.output.resolve():
parser.error("Input and output must be different files.")
try:
with args.input.open(encoding="utf-8-sig", newline="") as source:
rows, skipped = clean_rows(source)
with args.output.open("x", encoding="utf-8", newline="") as target:
writer = csv.DictWriter(target, fieldnames=["name", "email"])
writer.writeheader()
writer.writerows(rows)
except (OSError, ValueError, csv.Error) as error:
parser.exit(1, f"Error: {error}\n")
print(f"Wrote {len(rows)} contacts; skipped {skipped} rows.")
if __name__ == "__main__":
main()
3. Run it and inspect the result
From the project folder, run python3 clean_csv.py contacts.csv cleaned.csv. If your Python executable is named python or py, use that name instead. The expected terminal message is Wrote 2 contacts; skipped 3 rows.
name,email
Ada Santos,ada@example.com
Ben Cruz,ben@example.com
Open the result in a text editor and compare it with the input. The first valid Ada row wins. The name is normalized, email casing is consistent, and the invalid rows are absent. The input file’s contents have not changed.
Understand the decisions in the code
Header validation happens first. If the columns differ, the cleaner stops with an error instead of silently putting data into the wrong fields. If you need flexible headers, add an explicit mapping and tests for each supported variation.
newline=” delegates line endings to csv. This avoids adding unwanted blank lines on platforms with different newline conventions. The input encoding utf-8-sig accepts a UTF-8 byte-order mark while still accepting ordinary UTF-8 files.
A set tracks duplicate keys. Membership checks make the first-valid-row rule easy to express. The program retains cleaned rows in a list, so memory grows with the input. This is appropriate for a learning project, not a multi-gigabyte data import.
Output mode x refuses overwrite. Re-running the same command against an existing cleaned.csv ends with a file-exists error. Choose a new output filename or consciously move the old result aside. An output write interrupted by disk or system failure may leave a partial new file; inspect it before reuse.
Test the important cases
| Input condition | Expected result |
|---|---|
| The supplied five-row sample | Two contacts written; three rows skipped. |
| A quoted name containing a comma | The name remains a single field. |
| An extra field or missing email field | The malformed row is skipped. |
| Header is email,name | The command fails before creating output. |
| Input and output resolve to one path | The command refuses to run. |
| Output already exists | The existing output remains unchanged. |
| Header only | A header-only result is created with a zero-row summary. |
Troubleshooting
“Expected exactly these headers”: inspect the first row in a text editor. A semicolon-separated export, different capitalization, or trailing header space does not match the defined format. Decide whether to convert that export or deliberately extend the program.
“No such file or directory”: check the folder where the command is running. Quote paths that contain spaces. The output’s parent folder must already exist.
Unexpected characters: the example expects UTF-8. If an export uses another encoding, identify it from the source system and specify it intentionally. Ignoring encoding errors can silently discard characters.
Spreadsheet safety: CSV fields are text to this program, but spreadsheet applications can interpret formula-like values beginning with characters such as =. This cleaner does not neutralize spreadsheet formulas. Inspect untrusted results in a text editor, or design a separate export policy appropriate for the destination.
Add a report of rejected rows
Add a second output containing rejected rows and a reason for each rejection. Keep the original row number so a person can correct the source. Then add a --dry-run option that reports counts without writing files. Both changes improve explainability without turning the program into a large application.
Before handling real records, decide which values may be normalized, how duplicates should be resolved, where outputs may be stored, and when they should be deleted. A data cleaning program needs rules that match its real use case.
Download the complete example ZIP
The ZIP contains the original example files, a README, and an MIT license. No account or paid dependency is required for these examples.
References and verification
See the official Python csv documentation for reader and writer behavior. This guide was rewritten with AI assistance on October 19, 2026. The script was executed against the sample and tested for quoted commas, duplicates, malformed rows, invalid headers, empty files, and overwrite protection. The example ZIP includes the exact script shown here.
