python写入csv文件时携带双引号_为什么Python CSV阅读器忽略双引号字段?

I think this is probably something simple, but after an hour of searching, I've had no luck figuring out what I'm doing wrong.

I'm using the following code to read a CSV file - I have no problem reading the file, but when a line contains a field that is double-quoted because it contains the delimiter, the CSV reader ignores the double-quotes and parses the field into 2 separate fields.

Here's the code I'm using:

myReader = csv.reader(open(inPath, 'r'), dialect='excel', delimiter=',', quotechar='"')

for row in myReader:

print row,

print len(row)

My input:

hello, this is row 1, foo1

hello, this is row 2, foo2

goodbye, "this, is row 3", foo3

Which gives me:

['hello', ' this is row 1', ' foo1'] 3

['hello', ' this is row 2', ' foo2'] 3

['goodbye', ' "this', ' is row 3"', ' foo3'] 4

What do I need to change so it will recognize the double-quoted field as one field?

I'm using python version 2.6.1.

Thanks!

解决方案

If you look at the dialect that you're using, you'll notice that the excel dialect is

configured as follows:

class excel(Dialect):

"""Describe the usual properties of Excel-generated CSV files."""

delimiter = ','

quotechar = '"'

doublequote = True

skipinitialspace = False

lineterminator = '\r\n'

quoting = QUOTE_MINIMAL

Notice that skipinitialspace is set to False. Just pass that into your reader.

Oh and by the way, all the fields you've passed in are already the defaults when

using the excel dialect, which is the default dialect parameter passed to csv.reader

So, I would re-write your code like so:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值