#!/usr/bin/env python3 """Merge the till export and the newsletter export into one clean customer list. Usage: python merge_customers.py till_export.csv newsletter_export.csv Writes clean_customers.csv (one row per unique email) and skipped.csv (rows with no email). Duplicates are detected by email only, compared in lower case with spaces removed. When a customer is in both files the till row wins. Phone numbers are left untouched. """ import csv import sys from pathlib import Path OUT_COLUMNS = ["Name", "Email", "Last visit", "Phone"] def clean_email(value): return "".join((value or "").split()).lower() def clean_name(value): parts = " ".join((value or "").split()).split(" ") fixed = [] for p in parts: if not p: continue # keep particles like "van", "de" lower case, capitalise the rest fixed.append(p.lower() if p.lower() in {"van", "de", "der", "den", "te", "ten", "von"} else p[:1].upper() + p[1:].lower()) return " ".join(fixed) def read_rows(path): """Read a CSV and skip a leading non-header line such as 'Export date: ...'.""" text = Path(path).read_text(encoding="utf-8-sig") lines = text.splitlines() while lines and ("email" not in lines[0].lower()): lines.pop(0) # export-date line or blank line before the real header if not lines: raise SystemExit(f"{path}: could not find a header row containing 'Email'") reader = csv.DictReader(lines) # normalise header names so "E-mail", " email " etc. all work rows = [] for raw in reader: row = {} for k, v in raw.items(): if k is None: continue key = " ".join(k.replace("-", "").split()).lower() row[key] = (v or "").strip() rows.append(row) return rows def pick(row, *names): for n in names: if n in row and row[n]: return row[n] return "" def main(till_path, news_path, out_dir="."): till = read_rows(till_path) news = read_rows(news_path) seen = {} skipped = [] order = [] for r in till: email = clean_email(pick(r, "email")) record = { "Name": clean_name(pick(r, "name", "customer", "customer name")), "Email": email, "Last visit": pick(r, "last visit", "lastvisit", "last_visit"), "Phone": pick(r, "phone", "telephone", "mobile"), "_source": "till", } if not email: skipped.append({**record, "Reason": "no email (till)"}) continue if email not in seen: order.append(email) seen[email] = record # till always wins for r in news: email = clean_email(pick(r, "email")) name = pick(r, "name") or (pick(r, "first name", "firstname") + " " + pick(r, "last name", "lastname")).strip() record = {"Name": clean_name(name), "Email": email, "Last visit": "", "Phone": "", "_source": "newsletter"} if not email: skipped.append({**record, "Reason": "no email (newsletter)"}) continue if email in seen: continue # duplicate: till version kept seen[email] = record order.append(email) out_dir = Path(out_dir) with open(out_dir / "clean_customers.csv", "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=OUT_COLUMNS, extrasaction="ignore") w.writeheader() for e in order: w.writerow(seen[e]) with open(out_dir / "skipped.csv", "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=OUT_COLUMNS + ["Reason"], extrasaction="ignore") w.writeheader() for r in skipped: w.writerow(r) total_in = len(till) + len(news) dups = total_in - len(skipped) - len(order) print(f"rows in: {total_in} | no email: {len(skipped)} | duplicates removed: {dups} | unique customers: {len(order)}") print(f"written: {out_dir / 'clean_customers.csv'} and {out_dir / 'skipped.csv'}") if __name__ == "__main__": if len(sys.argv) < 3: print(__doc__) raise SystemExit(1) main(sys.argv[1], sys.argv[2])