Before you begin
- Python 3.12 or newer
Set up your example
- Save the complete code as csv-normalize-numbers.py in a working folder.
- Save the provided sample files in that same folder; run commands from that folder.
Sample files in this download:
- sample.csv
- lookup.csv
- second.csv
- wide.csv
- numbers.csv
- sample.tsv
Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is csv-normalize-numbers.py.
Run the script
python "csv-normalize-numbers.py" --input "numbers.csv" --column "amount" --output "numbers-clean.csv"If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.
What to expect
Convert locale-style numeric strings into plain decimal strings. The sample converts 1,250.50 into 1250.50.
The complete script
#!/usr/bin/env python3
'Remove explicit thousands separators'
import argparse
import json
from pathlib import Path
def write_json(path, value):
data = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
with Path(path).open("x", encoding="utf-8", newline="") as handle:
handle.write(data)
import csv
import random
from collections import Counter, defaultdict
from decimal import Decimal
from datetime import datetime
def read_csv(path, delimiter=","):
with Path(path).open(encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle, delimiter=delimiter)
fields = reader.fieldnames
if not fields or any(not f for f in fields) or len(set(fields)) != len(fields):
raise ValueError("Use a nonempty, unique header for every column.")
rows = list(reader)
if any(None in row or None in row.values() for row in rows):
raise ValueError("Every row must have exactly the header's number of cells.")
return fields, rows
def require(fields, names):
missing = set(names) - set(fields)
if missing:
raise ValueError("Missing columns: " + ", ".join(sorted(missing)))
def write_csv(path, fields, rows):
with Path(path).open("x", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fields)
writer.writeheader()
writer.writerows(rows)
def number(value):
result = Decimal(value or "0")
if not result.is_finite():
raise ValueError("Numbers must be finite.")
return result
def main():
parser = argparse.ArgumentParser(description='Remove explicit thousands separators')
parser.add_argument("--input", required=True, help="CSV input with a header")
parser.add_argument("--output", required=True, help="New destination file or directory")
parser.add_argument("--column", required=True)
parser.add_argument("--thousands", default=",")
parser.add_argument("--decimal", default=".")
args = parser.parse_args()
fields, rows = read_csv(args.input)
require(fields, [args.column])
if len(args.decimal)!=1 or args.thousands == args.decimal:
raise ValueError("Choose a one-character decimal mark distinct from the thousands mark.")
result_fields = fields
result = []
for row in rows:
copy = dict(row)
value = copy[args.column].strip()
if value:
value = value.replace(args.thousands, "") if args.thousands else value
copy[args.column] = str(number(value.replace(args.decimal, ".")))
result.append(copy)
write_csv(args.output, result_fields, result)
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError, TypeError, ArithmeticError, IndexError, LookupError) as exc:
raise SystemExit(str(exc))
Open source as plain text · Download source and sample files
How it works
- read_csv checks unique headers and row widths before processing.
- The selected thousands mark is removed and the selected decimal mark becomes a dot; the script does not infer locale or validate digit grouping.
- The sample converts 1,250.50 into 1250.50.
Make it your own
--decimal
Use --decimal , --thousands . for values such as 1.250,50.
Adapt the processing
Edit the stripped value expression to remove a known currency prefix before parsing.
Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.
If something goes wrong
A number is interpreted with the wrong magnitude.
Set both separators explicitly; do not mix locales in a single column.
The destination already exists.
Choose a new --output path. The script deliberately refuses to replace an existing result.
Reference & next steps
These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.
Copies a template for your own notes. It does not send anything.