You do not need pandas for everyday CSV and JSON jobs. Python's standard library handles most of them in a few lines. These are the recipes I reuse.
1. Read a CSV into dictionaries
import csv with open("people.csv", newline="", encoding="utf-8-sig") as f: rows = list(csv.DictReader(f)) print(rows[0]) # {'id': '1', 'email': 'a@x.com'} -
newline=""lets the csv module handle line endings correctly. -
utf-8-sigremoves the invisible BOM that Excel adds, so your first column is not namedid. - All values are strings. Convert with
int()orfloat()where needed.
2. Remove duplicate rows (by a column)
seen, unique = set(), [] for row in rows: key = row["email"].strip().lower() if key in seen: continue seen.add(key) unique.append(row) print(len(rows), "->", len(unique)) Normalising the key (strip().lower()) catches A@x.com and a@x.com as the same person.
3. Write rows back to CSV
with open("clean.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=rows[0].keys()) writer.writeheader() writer.writerows(unique) 4. CSV to JSON
import json with open("clean.json", "w", encoding="utf-8") as f: json.dump(unique, f, indent=2, ensure_ascii=False) ensure_ascii=False keeps non-English text (such as Tamil) readable instead of escaping it as க.
5. JSON to CSV (flat objects)
import csv, json data = json.load(open("data.json", encoding="utf-8")) if isinstance(data, dict): data = [data] columns = list(dict.fromkeys(k for row in data for k in row)) with open("data.csv", "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=columns) w.writeheader() for row in data: w.writerow({k: json.dumps(v) if isinstance(v, (dict, list)) else v for k, v in row.items()}) The dict.fromkeys trick collects every column in first-seen order, even when objects have different keys. Nested lists or dicts are stored as JSON text in the cell.
6. Handle bad data safely
def to_int(value, default=0): try: return int(str(value).strip()) except ValueError: return default Wrap conversions so one bad row does not crash the whole job, and log what you skipped.
Common mistakes
- Opening the file without
newline="", which creates blank lines on Windows. - Forgetting the encoding, which breaks on non-English text.
- Comparing strings that differ only in case or spaces.
- Loading a huge file with
list(...). For big files, loop over the reader and write as you go. - Overwriting your only copy. Write to a new file first.
Ready-made versions
I packaged the CSV dedupe and JSON to CSV scripts (with usage help) in a free scripts repo: https://gitlab.com/yogeshwaran-tech-tools/python-automation-scripts and a larger set of ten here: https://yogeshwarantechtools.myinstamojo.com/product/python-automation-scripts-pack-10-ready-to-r
Written by Yogeshwaran Tech Tools. Corrections welcome.
