DEV Community

BotHot
BotHot

Posted on

Normalize decimal-comma prices in a CSV before a Shopify import (Python, stdlib only)

Product exports from German or French spreadsheets often contain prices like 12,90 or 1.299,00 €. Shopify expects 12.90 and 1299.00, so an import with the wrong format fails or gives wrong prices. Here is a small script that normalizes one price column and tells you which rows it could not parse.

The rules

  • Remove spaces, non-breaking spaces and currency symbols.
  • If both , and . appear, the last one is the decimal separator.
  • If only a comma appears, it is the decimal separator.
  • Anything that is not digits with at most two decimals afterwards is reported, not guessed.

The script

import csv, re, sys

def normalize(value):
    v = value.strip().replace("\u00a0", "").replace(" ", "")
    v = re.sub(r"[€$£]|EUR|USD", "", v)
    if not v:
        return None
    if "," in v and "." in v:
        if v.rfind(",") > v.rfind("."):
            v = v.replace(".", "").replace(",", ".")
        else:
            v = v.replace(",", "")
    elif "," in v:
        v = v.replace(",", ".")
    if not re.fullmatch(r"\d+(\.\d{1,2})?", v):
        return None
    return f"{float(v):.2f}"

def main(src, dst, column):
    bad = []
    with open(src, newline="", encoding="utf-8-sig") as f, \
         open(dst, "w", newline="", encoding="utf-8") as out:
        r = csv.DictReader(f)
        w = csv.DictWriter(out, fieldnames=r.fieldnames)
        w.writeheader()
        for n, row in enumerate(r, start=2):
            fixed = normalize(row[column])
            if fixed is None:
                bad.append((n, row[column]))
            else:
                row[column] = fixed
            w.writerow(row)
    for n, raw in bad:
        print(f"line {n}: cannot parse {raw!r}")
    print(f"done, {len(bad)} problem value(s)")

if __name__ == "__main__":
    main(*sys.argv[1:4])
Enter fullscreen mode Exit fullscreen mode

Usage and test run

python fix_prices.py products.csv products_fixed.csv "Variant Price"
Enter fullscreen mode Exit fullscreen mode

I tested it with this input:

Handle,Title,Variant Price
mug,Mug,"12,90"
tee,Tee,"1.299,00 €"
cap,Cap,"1,299.50"
bag,Bag,abc
sock,Sock,"7,5"
Enter fullscreen mode Exit fullscreen mode

Output:

line 5: cannot parse 'abc'
done, 1 problem value(s)
Enter fullscreen mode Exit fullscreen mode

The fixed file contains 12.90, 1299.00, 1299.50 and 7.50; the unparseable row is left unchanged so you can fix it by hand.

Limits

It handles one column and assumes at most two decimals. Prices with three decimals or unusual formats are reported instead of converted, which is intentional: a wrong price is worse than a flagged one. Always check a few rows against the original before importing.

Top comments (0)