nextdoordoc
nextdoordoc

Reputation: 1767

python csv module omits first letter '0'

I am trying to make csv file by csv module.

The problem is exported csv file contains row of which first letter '0' omitted..

The code:

import csv
from django.utils.encoding import smart_str
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=customer_email_who_reserved.csv'
writer = csv.writer(response, csv.excel)
writer.writerow([
    smart_str(u"email"),
    smart_str(u"phonenumber"),
])
for obj in queryset:
    writer.writerow([
        smart_str(obj.email),
        '010',
    ])

And the weird thing is output of phonenumber row is "10" instead of "010".

How can I fix this problem?

Thanks in advance!

Upvotes: 0

Views: 103

Answers (1)

marabu
marabu

Reputation: 1196

Leading zeroes may be gone if you open a CSV file with Excel, which is trying to be smart guessing a cell format. Use a text editor to see what csv.writer really produced. Prepend a tab character to outsmart Excel, so a numeric string is shown as Text.

Upvotes: 1

Related Questions