#!/usr/bin/env python3 """Turn a Mailchimp audience export CSV into a listmonk import CSV. python3 mailchimp-to-listmonk.py subscribed_email_audience_export_*.csv > subscribers.csv listmonk imports three columns: email, name and attributes (JSON). This keeps the email address, joins First Name and Last Name into the name, and puts every other non-empty column under attributes.mailchimp, with TAGS as a list. Opt-in and confirmation times come along as your consent record. Columns that only mean something inside Mailchimp (LEID, EUID, ratings, geolocation) are dropped. Standard library only; reads UTF-8 with or without a BOM. """ import csv, json, re, sys DROP = {"leid", "euid", "member_rating", "latitude", "longitude", "gmtoff", "dstoff", "timezone", "cc", "region", "last_changed"} def key(col): return re.sub(r"[^a-z0-9]+", "_", col.strip().lower()).strip("_") def tags(value): # Mailchimp writes tags as "Tag one","Tag two" inside one cell. found = re.findall(r'"([^"]*)"', value) return found or [t.strip() for t in value.split(",") if t.strip()] def convert(path, out): with open(path, newline="", encoding="utf-8-sig") as f: rows = csv.DictReader(f) cols = {key(c): c for c in rows.fieldnames or []} email_col = cols.get("email_address") or cols.get("email") if not email_col: sys.exit(f"{path}: no 'Email Address' column; is this a Mailchimp audience export?") n = 0 for row in rows: email = (row.get(email_col) or "").strip() if not email: continue first = (row.get(cols.get("first_name", ""), "") or "").strip() last = (row.get(cols.get("last_name", ""), "") or "").strip() extra = {} for k, col in cols.items(): v = (row.get(col) or "").strip() if not v or col in (email_col,) or k in DROP or k in ("first_name", "last_name"): continue extra[k] = tags(v) if k == "tags" else v out.writerow([email, " ".join(p for p in (first, last) if p), json.dumps({"mailchimp": extra}, ensure_ascii=False)]) n += 1 print(f"{path}: {n} rows", file=sys.stderr) def main(): if len(sys.argv) < 2: sys.exit(__doc__) out = csv.writer(sys.stdout) out.writerow(["email", "name", "attributes"]) for path in sys.argv[1:]: convert(path, out) if __name__ == "__main__": main()