【问题标题】:How to force csv library to preserve leading zeroes?如何强制 csv 库保留前导零?
【发布时间】:2018-10-09 18:11:20
【问题描述】:

我正在使用 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)

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

【问题讨论】:

  • csv 没有丢弃前导零。你是。你为什么打电话给int
  • 另外except ValueError, e 在 Python 3 中无效,因此您可能运行的不是您认为的 Python 版本。
  • 它仍然将这些值视为整数。尝试写整行。除非您想过滤掉某些列,否则迭代行中的每个列并追加都无济于事

标签: python python-2.7 csv


【解决方案1】:

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

import csv
with open('C:\\Temp\\inputfile.csv', 'rb') as f_input:
    with 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:
            print(row_input)
            csv_output.writerow(row_input)

【讨论】:

  • 我刚刚发现了一些奇怪的东西。如果我将文件的编码更改为 ANSI,您的代码就可以工作。如果我将文件保存为 UTF8,它会失败。感谢您的帮助!
  • 还有一个小问题,所有列都被引号括起来。第一列 CustomerId 不需要用引号括起来。
【解决方案2】:

不要将值转换为ints。

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)

【讨论】:

  • 我不小心把它标记为python3,但它是python 2。你的代码和我的代码做的完全一样。
猜你喜欢
  • 2011-10-01
  • 2017-05-05
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2012-11-28
  • 1970-01-01
相关资源
最近更新 更多