Preserve leading-zero identifiers during CSV preflight
Also published in our Blogger archive.
Quick answer
CSV readers produce text, which lets a validator inspect identifier spelling before numeric conversion changes it.
Example
The regex accepts exactly five digits beginning with zero. 00123 remains a string and passes; 123 and 00A are listed unchanged as failures. No integer is created anywhere in the example.
import csv, io, re
rows = list(csv.DictReader(io.StringIO('account\n00123\n123\n00A\n')))
pattern = re.compile('0\\d{4}$')
bad = [r['account'] for r in rows if not pattern.fullmatch(r['account'])]
assert bad == ['123', '00A']
print('invalid:', bad)
Expected stdout:
invalid: ['123', '00A']
Reading the result
The pattern is only a sample identifier contract. Define permitted length, prefix, and alphabet with the data owner instead of reusing it for unrelated account numbers.
Avoid spreadsheet-style automatic typing before this preflight. Once a value becomes an integer, an absent leading zero cannot be recovered from the converted value alone.
The failure list maintains source spelling. That gives the exporter owner enough evidence to correct an ID without the validator inventing a normalized replacement.
Sources
- Python csv module documentation
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.