在Python的字段中使用逗号读取CSV文件 [英] Read CSV file with comma within fields in Python

查看:1144
本文介绍了在Python的字段中使用逗号读取CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取一个包含逗号的字段的CSV文件,所以我用双引号引起了包含逗号的字段,例如:

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


$ b b

但是当我尝试在Python中读取文件时,我得到用逗号分隔的字段,如下所示:

  row [0] = 1 
row [1] = text1
row [2] = text2
row [3] = text3
row [4] = text4
row [5] = a
row [6] = b
row [7] = c

我正在用以下代码读取CSV文件:

  info = csv.reader(open /info.csv'))
for row in info:
print row [0] +*+ row [1] ...
pre>

是否可以读取包含逗号的双引号字段?

解决方案

Python csv 模块实际上确实支持引用的字段,即使默认情况下。这里的问题是Python默认不会跳过这个空格,所以你需要使用 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']]


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']]

这篇关于在Python的字段中使用逗号读取CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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