如何强制csv库保留前导零?

时间:2018-10-09 18:11:21

标签: python python-2.7 csv

我正在使用csv库对所有非数字值应用双引号。 我来源中的一列是美国邮政编码。

我的源文件看起来像这样。

CustomerId,CustomerName,Street ,City,State,Zip Code
513916,Indian Tribal Council,1487 S. RESERVATION ROAD,PORTERVILLE,CA,93257
1176103,Iberdrola USA,100 MAIN STREET,New Gloucester,ME,04260

一旦我在文件上应用了csv代码。

文件开始看起来像这样。

"CustomerId","CustomerName","Street ","City","State","Zip Code"
513916,"Tule River Indian Tribal Council","1487 S. RESERVATION ROAD","PORTERVILLE","CA",93257
1176103,"Iberdrola USA","100 MAIN STREET","New Gloucester","ME",4260

这是代码,我正在使用:

with open('C:\\Temp\\inputfile.csv', 'rb') as f_input, \
    open('C:\\Temp\\outputfile.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    csv_output = csv.writer(f_output, quoting=csv.QUOTE_NONNUMERIC)

    for row_input in csv_input:
        row_output = []
        for col in row_input:
            try:
                row_output.append(int(col))
            except ValueError, e:
                row_output.append(col)
        csv_output.writerow(row_output)

是否有任何修复方法可以保留输入文件中的前导零?

2 个答案:

答案 0 :(得分:0)

请勿将值转换为int

print(int("04260"))
>>> 4260

只需删除try/except块。

with open('C:\\Temp\\inputfile.csv', 'rb') as f_input, \
    open('C:\\Temp\\outputfile.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    csv_output = csv.writer(f_output, quoting=csv.QUOTE_NONNUMERIC)

    for row_input in csv_input:
        row_output = []
        for col in row_input:
            row_output.append(col)
        csv_output.writerow(row_output)

答案 1 :(得分:0)

无需迭代每一列,它就会完美地发出代码。在2.7上测试

*/