DEV Community

BotHot
BotHot

Posted on

Find Shopify CSV rows where the compare-at price is not above the price (Python)

Shopify accepts a product CSV where "Variant Compare At Price" is lower than or equal to "Variant Price". The import goes through, but the product then shows no strike-through price, or a "sale" that is not a sale. In a file with a few hundred rows this is easy to miss.

Here is a small script that lists every row where the compare-at price is not above the price. It uses only the standard library (the decimal module avoids float rounding surprises).

import csv
import sys
from decimal import Decimal, InvalidOperation

PRICE = "Variant Price"
COMPARE = "Variant Compare At Price"


def parse(value):
    value = (value or "").strip()
    if not value:
        return None
    try:
        return Decimal(value)
    except InvalidOperation:
        return "bad"


def check(path):
    problems = []
    with open(path, newline="", encoding="utf-8-sig") as f:
        reader = csv.DictReader(f)
        for line, row in enumerate(reader, start=2):
            price = parse(row.get(PRICE))
            compare = parse(row.get(COMPARE))
            if compare is None:
                continue  # no compare-at price: nothing to check
            handle = row.get("Handle", "")
            if price in (None, "bad") or compare == "bad":
                problems.append((line, handle, "unreadable price or compare-at value"))
            elif compare <= price:
                problems.append((line, handle, f"compare-at {compare} is not above price {price}"))
    return problems


if __name__ == "__main__":
    found = check(sys.argv[1])
    for line, handle, msg in found:
        print(f"line {line} ({handle}): {msg}")
    print(f"{len(found)} problem(s) found")
    sys.exit(1 if found else 0)
Enter fullscreen mode Exit fullscreen mode

Try it

Save it as check_compare_at.py and run python check_compare_at.py products.csv. With this small test file:

Handle,Title,Variant Price,Variant Compare At Price
mug,Mug,12.00,15.00
shirt,Shirt,20.00,20.00
cap,Cap,9.50,8.00
bag,Bag,30.00,
pin,Pin,abc,5.00
Enter fullscreen mode Exit fullscreen mode

the output is:

line 3 (shirt): compare-at 20.00 is not above price 20.00
line 4 (cap): compare-at 8.00 is not above price 9.50
line 6 (pin): unreadable price or compare-at value
3 problem(s) found
Enter fullscreen mode Exit fullscreen mode

Notes

  • Line numbers match the line in the file (the header is line 1), so you can jump straight to the row in your editor.
  • Rows without a compare-at price are skipped on purpose: that is a normal, non-sale product.
  • If your export uses decimal commas (12,50), normalize them first, otherwise those rows are reported as unreadable. I covered that in a previous post.
  • The exit code is 1 when problems exist, so you can use the script in a pre-import check or a simple CI step.
  • It only reads the file and never changes it.

Top comments (0)