Sort CSV by a numeric column with Python
Writes ascending numeric amounts, with empty or invalid amounts last and ties in source order. Cell strings, including leading zeros, stay unchanged.
Before you start
- Python 3.10 or later. Run in a working folder with a backup of your source; output files may be replaced unless opened in exclusive mode.
- Place input.csv in that folder. Examples use UTF-8, a comma delimiter and a header row. Column-specific recipes use id,label,amount,status,note; adapt names to your file.
python3 - <<'PY'
import csv
with open("input.csv", encoding="utf-8-sig", newline="") as source:
table = list(csv.reader(source, strict=True))
if not table:
raise ValueError("Expected a header row")
headers, rows = table[0], table[1:]
if any(len(row) != len(headers) for row in rows):
raise ValueError("Every record must match the header width")
from decimal import Decimal, InvalidOperation
amount_column = headers.index("amount")
def sort_key(row):
try:
value = Decimal(row[amount_column])
if value.is_finite():
return (False, value)
except InvalidOperation:
pass
return (True, Decimal(0))
rows.sort(key=sort_key)
with open("output.csv", "w", encoding="utf-8", newline="") as target:
writer = csv.writer(target)
writer.writerow(headers)
writer.writerows(rows)
print(f"Wrote {len(rows)} records to output.csv")
PYLimits and output
- CSV has no stored type schema. Python keeps fields as strings until an example explicitly converts a value. These recipes do not add spreadsheet formula protection; import sensitive-looking strings as text in spreadsheets.
- For literal text sorting, use key=lambda row: row[amount_column]. Text collation differs from the browser. For descending numeric order with blanks last, negate only the finite numeric value rather than reversing the entire result.
- This recipe retains the parsed table in memory; use a streaming approach for files that do not fit.
Documentation: Python CSV reader and writer