python导出csv不带引号,python的csv阅读器可以保留引号吗?

在Python中使用CSV阅读器时,遇到一个问题:想要保留字段内的双引号,但CSV.reader默认会去除。由于CSV解析的引号处理部分在C语言实现,无法直接修改。因此,必须自定义一个解析器来满足需求,或者考虑修改Python源代码,但这可能影响代码的维护性。目前没有直接的方法可以简单地使CSV.reader按预期工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I want to use the python CSV reader but I want to leave the quotes in. That is I want:

>>> s = '"simple|split"|test'

>>> reader = csv.reader([s], delimiter='|', skipinitialspace=True)

>>> reader.next()

['"simple|split"', 'test']

But I actually get:

['simple|split', 'test']

In my case I want the quoted string to be passed on still quoted.

I know the CSV reader is working as intended and my use case is an abuse of it, but is there some way to bend it to my will? Or do I have to write my own string parser?

解决方案

You're going to have to write your own parser, as the part of the module that backs parsing and quotes is in the C side of things, in particular parse_process_char located in Modules/_csv.c:

else if (c == dialect->quotechar &&

dialect->quoting != QUOTE_NONE) {

if (dialect->doublequote) {

/* doublequote; " represented by "" */

self->state = QUOTE_IN_QUOTED_FIELD;

}

else {

/* end of quote part of field */

self->state = IN_FIELD;

}

}

else {

/* normal character - save in field */

if (parse_add_char(self, c) < 0)

return -1;

}

That "end of quote part of field" section is what's chomping your double quote. On the other hand, you might be able to kill that else conditional and rebuild the python source code. However that's not all that maintainable to be honest.

Edit: Sorry I meant add the bit from the last else before self->state = IN_FIELD so it adds the quote in.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值