KlaroKit
← All posts

Why ZIP Codes Lose Their Leading Zeros in CSV Files, and How to Stop It

A ZIP code like 02134 turns into 2134 because a CSV file stores no types. Whatever opens or imports the file has to guess what each column is, and "02134" looks like a number. Numbers don't have leading zeros, so the zero is dropped. The most common culprit is double-clicking the file so it opens in Excel. To stop it, tell every tool the file passes through that the ZIP column is text: your spreadsheet, your import script and your database column. Then check the lengths before you load.

Why does a CSV file drop the leading zero?

A CSV file is plain text. The lines below don't say that zip is text and order_total is a number. They are just characters separated by commas:

customer_id,name,zip,order_total
000417,Dana Reyes,02134,84.50

Every tool that reads the file decides for itself what each column is. Most of them look at the values, see only digits, and decide "number." Once a value is a number, 02134 and 2134 are the same thing, and the zero has nowhere to live.

This affects a lot of real addresses. US ZIP codes in New England, New Jersey and Puerto Rico start with 0, and Puerto Rico's start with 00. Puerto Rico's 00601 can come out as 601, with two digits gone.

Where does the guess happen?

There are usually three places, and a file can pass through all of them on the way to its final table.

Opening the file in a spreadsheet. On many computers, double-clicking a CSV opens it in Excel, which converts digit-only values to numbers right away. The damage becomes permanent when someone presses Save, because the file is rewritten with 2134 in it. Nobody did anything wrong. They opened a file and saved it. Excel for Microsoft 365 and Excel 2024 have a setting to keep leading zeros (File > Options > Data > Automatic Data Conversion), but you can't count on everyone who touches the file having it turned on.

Automatic type detection in an importer or script. Most import tools look at a column's values and pick a type. Python's pandas does the same:

import pandas as pd

df = pd.read_csv("customers.csv")
print(df["zip"].head(1))   # 2134, stored as int64

If the column has any blank values, pandas reads it as decimals instead, so you get 2134.0. That is even further from the original.

A numeric database column. If someone created the destination column as integer, the database converts the text on load. Postgres will accept '02134' into an integer column and store 2134 without complaint. Every step before it can be correct, and this one still drops the zero.

Can't you just pad the zeros back later?

Sometimes. It is riskier than it looks.

Padding can cut values short. Postgres's lpad pads short strings, but it also truncates long ones to the length you give it. Run it across a column that mixes five-digit ZIPs and ZIP+4 codes, and the longer ones lose their last four digits:

SELECT lpad('2134', 5, '0');        -- '02134'  (good)
SELECT lpad('02134-5678', 5, '0');  -- '02134'  (the +4 part silently cut)

Not every value is a US ZIP. A Canadian postal code like K1A 0B1 should not be padded at all, and a short number might be a typo rather than a lost zero.

For anything without a fixed length, the information is gone. A US ZIP is always five digits, so you know how many zeros to add back. Account IDs and phone numbers don't work that way:

Original value After a numeric import Can you restore it?
02134 (ZIP) 2134 Yes, pad to 5
000417 (account ID) 417 No: was it 0417, 00417 or 000417?
0417 (different account ID) 417 No, and it now collides with the one above

Two different customers now share an ID. Joins, deduplication and lookups will quietly treat them as one.

If your ZIPs are already damaged, repair only the rows you are sure about. Limit the fix to US addresses with three or four digits and nothing else:

UPDATE customers
SET zip = lpad(zip, 5, '0')
WHERE country = 'US'
  AND zip ~ '^[0-9]{3,4}$';

For IDs that have already collided, go back to the original source file. Padding can't separate them.

How do you keep the column as text from start to finish?

Don't double-click the CSV. In Excel, use Data > From Text/CSV instead. In the preview, either turn off automatic data type detection in the last dropdown so every column loads as text, or choose Transform Data and set the ZIP column's data type to Text before loading. In Google Sheets, use File > Import and turn off the option that converts text to numbers and dates. If you only need to look at the file, a text editor is safer than a spreadsheet.

Tell your script the type. Don't let it guess:

df = pd.read_csv("customers.csv", dtype={"zip": "string", "customer_id": "string"})

Make the destination column text, with a rule. A text column keeps the zeros. A CHECK constraint rejects anything that doesn't look like a ZIP:

CREATE TABLE customers (
  customer_id text PRIMARY KEY,
  zip text CHECK (zip ~ '^[0-9]{5}(-[0-9]{4})?$')
);

If you have international addresses, drop the pattern, or store the country alongside the postal code and validate per country.

Check lengths before you load. Load the file into a staging table with every column as text, then look for anything odd:

SELECT zip, length(zip) AS len, count(*)
FROM staging_customers
WHERE zip !~ '^[0-9]{5}(-[0-9]{4})?$'
GROUP BY zip, length(zip)
ORDER BY count(*) DESC;

A run of three- and four-digit values means something upstream treated the column as a number, often a spreadsheet. It is much cheaper to find that here than in a stack of returned mail.

Treat identifiers as labels, not numbers. Ask whether you would ever add, subtract or average the value. Nobody averages ZIP codes, phone numbers or account IDs. If the answer is no, it's a label, so store it as text. That habit prevents most of the trouble above, and it is a good rule to write into your field mappings. Our plain-English guide to data mapping covers how those mappings fit together.

The type decision deserves a human look even when a tool suggests it. A column full of digits looks like a number to anything that matches on shape alone. We cover that in where auto-mapping CSV columns quietly goes wrong. We're building KlaroKit, a data mapping tool, around that idea: it suggests how fields line up, and nothing is applied until a person approves it. It isn't released yet. If you'd like to hear when early access opens, you can join the waitlist. People on the list get one email when it opens, and a launch discount.

FAQ

Does putting quotes around the ZIP in the CSV keep the zero?

Usually not. In a CSV, quotes only mark where a field starts and ends. Excel and pandas still read "02134" as a number. The Excel trick of writing ="02134" does show the zero in Excel, but every other tool reads that literal text, equals sign and all.

Does saving as .xlsx instead of CSV keep the leading zeros?

It can, because an .xlsx file stores each cell's type and a CSV doesn't. The zeros survive only if the cells were text before you saved. If Excel already converted them to numbers, the .xlsx file faithfully stores the wrong value.

Is formatting the column as "00000" in Excel a real fix?

No, it only changes what you see. The cell shows 02134, but the value underneath is still the number 2134. A script or database that reads the workbook will usually get 2134. Format the column as Text before the data goes in.

Do JSON files have the same problem?

Less often. JSON separates strings from numbers, and a number with a leading zero isn't valid JSON. A well-made export writes "zip": "02134" in quotes, and the zero is safe. The risk comes back if the receiving system maps that string into a numeric field, so check the destination type there too.