Python CSV:字段开头包含引号 [英] Python CSV : field containing quotation mark at the beginning

查看:365
本文介绍了Python CSV:字段开头包含引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取包含以下内容的CSV文件:

I am trying to read a CSV file containing a line like following:

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

引号存在问题(有六个字段,但是它们被检索为五个字段,例如"test",将test读取为单个字段).

There is a problems with the quotation marks (There are six fields, but they are retrieved as five fields, as "test,"test is read as a single field).

我尝试如下修改条目,但是仍然无法获取引号:

I have tried modifying the entry as follows, but I still can't retrieve the quotation mark:

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文件:

I'm reading CSV file this way:

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

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

推荐答案

默认情况下,"引号.使用

By default " is the quoting character of Python's csv module. Use

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

禁用此默认设置.您提供的示例将产生记录

to disable this default. The example you gave will result in the record

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

这篇关于Python CSV:字段开头包含引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆