python处理csv文件字段中含有逗号的情况_在Python的字段中使用逗号读取CSV文件

这篇博客介绍了在Python中处理CSV文件时遇到的问题,即字段内包含逗号但已用双引号括起。默认情况下,Python的csv模块会将逗号作为字段分隔符,导致内容被错误解析。解决方案是使用`skipinitialspace=True`参数来忽略字段间的空格,正确读取双引号内的完整内容。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I need to read a CSV file which has fields that have a comma, so I have double quoted the fields which contains commas, such as:

1, "text1,text2", "text3, text4", a, b, c

But when I try to read the file in Python I get the fields separated by the commas, as following:

row[0] = 1

row[1] = text1

row[2] = text2

row[3] = text3

row[4] = text4

row[5] = a

row[6] = b

row[7] = c

I am reading the CSV file with the following code:

info = csv.reader(open('./info.csv'))

for row in info :

print row[0] + " * " + row[1] ...

Is it possible to read double quoted fields which contains a comma?

解决方案

The Python csv module actually does support quoted fields, even by default. Your problem here is that Python by default does not skip the space, so you need to use skipinitialspace=True.

>>> s = StringIO.StringIO('1, "text1,text2", "text3, text4", a, b, c')

>>> list(csv.reader(s, skipinitialspace=True))

[['1', 'text1,text2', 'text3, text4', 'a', 'b', 'c']]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值