【问题标题】:Python CSV : field containing quotation mark at the beginningPython CSV:开头包含引号的字段
【发布时间】:2012-02-09 10:55:20
【问题描述】:

我正在尝试读取包含如下行的 CSV 文件:

test,"test,"test,test,test,test

引号有问题(有六个字段,但是检索为五个字段,如“test”,test被读取为单个字段)。

我已尝试将条目修改如下,但仍然无法检索引号:

test,""test,""test,test,test,test  # quotation marks disappear when the entry is read.

test,\"test,\"test,test,test,test  # backslashes are also retrieved; escaping doesn't seem to work.

我正在以这种方式读取 CSV 文件:

info_source = csv.reader(open('.info.csv'), skipinitialspace=True)

for row in ling_info_source:
    data = row[1].strip()
    ...

【问题讨论】:

    标签: python csv quotation-marks


    【解决方案1】:

    默认情况下," 是 Python 的 csv 模块的 quoting character。使用

    csv.reader(open('.info.csv'), skipinitialspace=True, quotechar=None)
    

    禁用此默认设置。您给出的示例将导致记录

    ['test', '"test', '"test', 'test', 'test', 'test']
    

    【讨论】:

    • 这个解决方案的问题是我无法读取案例,例如:[test, "test, "test, "commaToRead,commaToRead", test, test]。对于这种情况,我应该阅读:[test]["test]["test]["commaToRead,commaToRead"][test][test]。有可能吗?
    • @David:这是模棱两可的。解析器应该如何知道哪些双引号是用来引用的,哪些不是?
    • 我想我应该添加它,因为这是我必须测试以澄清的东西:引用字符仅在它出现在分隔符之后才适用。也就是说,引用字符必须是新分隔部分中的第一个字符,才能使文本中的任何分隔符无效。
    • 我认为解析器应该看到 "test, "test, 引号后跟 test"commaToRead,commaToRead", 引号后跟逗号
    【解决方案2】:

    您可以将quoting=csv.QUOTE_NONE 参数添加到reader()

    【讨论】:

    • 虽然在我的回答中使用quotechar=None 效果很好,但quoting=csv.QUOTE_NONE 似乎是在阅读器中禁用引用的记录方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2020-03-08
    • 2015-07-06
    • 2017-03-17
    • 1970-01-01
    • 2022-11-05
    相关资源
    最近更新 更多