【问题标题】:Why is the Python CSV reader ignoring double-quoted fields?为什么 Python CSV 阅读器会忽略双引号字段?
【发布时间】:2011-07-29 22:17:56
【问题描述】:

我认为这可能很简单,但经过一个小时的搜索,我没有弄清楚我做错了什么。

我正在使用以下代码读取 CSV 文件 - 我在读取文件时没有问题,但是当一行包含一个因包含分隔符而被双引号引起来的字段时,CSV 阅读器会忽略双引号并将字段解析为 2 个单独的字段。

这是我正在使用的代码:

myReader = csv.reader(open(inPath, 'r'), dialect='excel', delimiter=',', quotechar='"')
for row in myReader:
    print row,
    print len(row)

我的意见:

hello, this is row 1, foo1
hello, this is row 2, foo2
goodbye, "this, is row 3", foo3

这给了我:

['hello', ' this is row 1', ' foo1'] 3
['hello', ' this is row 2', ' foo2'] 3
['goodbye', ' "this', ' is row 3"', ' foo3'] 4

我需要进行哪些更改才能将双引号字段识别为一个字段? 我使用的是 python 2.6.1 版。

谢谢!

【问题讨论】:

    标签: python csv


    【解决方案1】:

    如果您查看您正在使用的方言,您会注意到 excel 方言是 配置如下:

    class excel(Dialect):
        """Describe the usual properties of Excel-generated CSV files."""
        delimiter = ','
        quotechar = '"'
        doublequote = True
        skipinitialspace = False
        lineterminator = '\r\n'
        quoting = QUOTE_MINIMAL
    

    请注意,skipinitialspace 设置为 False。只需将其传递给您的读者即可。 哦,顺便说一句,你传入的所有字段都已经是默认值了 使用excel 方言,这是传递给csv.reader 的默认方言参数

    所以,我会像这样重写你的代码:

    >>> with open(inPath) as fp:
    >>>     reader = csv.reader(fp, skipinitialspace=True)
    >>>     for row in reader:
    >>>         print row,
    >>>         print len(row)
    ['hello', 'this is row 1', 'foo1'] 3
    ['hello', 'this is row 2', 'foo2'] 3
    ['goodbye', 'this, is row 3', 'foo3'] 3
    

    【讨论】:

      【解决方案2】:

      这是因为您的 csv 在引号前有空格:

      one0, one1, one2
      two0, two1, two2
      tre0, "tr,e1", tre2
      

      one0,one1,one2
      two0,two1,two2
      tre0,"tr,e1",tre2
      

      您需要先删除这些多余的空格。

      【讨论】:

      • 错了:csv.reader()skipinitialspace 选项来处理这些空白。
      猜你喜欢
      • 2021-01-21
      • 2020-02-21
      • 2017-07-25
      • 2015-10-09
      • 1970-01-01
      • 2014-02-26
      • 2017-08-08
      • 2017-01-23
      相关资源
      最近更新 更多