'Keep leading zeros in csv and excel in Python
I want the '000100' value keep the same in csv file but it changes to 100 in Excel.

Solution 1:[1]
The problem is with excel not considering those zeros, not really the csv. I found this somewhere, perhaps add it and see if it works?
df['column']=df['column'].apply('="{}"'.format)
Solution 2:[2]
The csv module isn't doing this, it's the spreadsheet program you loaded it with (the csv module was passed a string after all; it can't even consider dropping leading zeroes). If you open the CSV file in a plain text editor you'll see this.
Given that, your options are:
- Figure out if your spreadsheet program can customize the import rules to avoid screwing with the data (or after loading, change the column's interpretation rules to something that explicitly says it's text, not a numeric or auto-deduced type).
- If the program supports recognizing quoted fields as non-numeric, pass
quoting=csv.QUOTE_NONNUMERICto thecsv.writerso it quotes all the fields that aren't of numeric type (e.g. these strings) and hopefully stop the editor from treating them as numeric (causing the leading zero stripping).
Solution 3:[3]
The csv is probably fine. But you should open it in a text editor (not Excel) and see for yourself.
Excel will try to remove leading zeros, but you can force them back by adding a custom format to your column:
A filter of 000000 will force 6 digits to be shown:
- Highlight all the cells you want to format:
- Click on text text format box
- Select
more number formats
- Select
custom
- In the
Type:box, enter000000:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | diana18 |
| Solution 2 | ShadowRanger |
| Solution 3 | Freddy Mcloughlan |






