python导出csv不带引号,python csv writer不需要时添加引号

I am having issues with writing json objects to a file using csv writer, the json objects seem to have multiple double quotes around them thus causing the json objects to become invalid, here is the result:

"{""user.CustomAttribute.ISOLanguageCode"": ""en"", ""user.Email"": ""emzy1786@googlemail.com""

what I want is

{"user.CustomAttribute.ISOLanguageCode": "en", "user.Email"": "emzy1786@googlemail.com"}

here is how I open the file, perhaps there is an argument I can pass to prevent this from happening?

file = csv.writer(open(localResultPath + ".txt",'ab'),delimiter = '|')

here is how I write to the file, the last append adds the json as a string

list.append(pk)

list.append(email)

list.append(json)

file.writerow(list)

解决方案

Switch off auto-quoting with quoting=csv.QUOTE_NONE, and set quotechar to the empty string:

file = csv.writer(open(localResultPath + ".txt",'ab'),

delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')

Even with csv.QUOTE_NONE the csv.writer() will still want to quote the quotechar if left set to anything but an empty string, if present in the value. The default quote character is " and JSON values are full of those.

Demo:

>>> from cStringIO import StringIO

>>> import csv

>>> f = StringIO()

>>> writer = csv.writer(f, delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')

>>> writer.writerow(['{"user.CustomAttribute.ISOLanguageCode": "en"}'])

>>> f.getvalue()

'{"user.CustomAttribute.ISOLanguageCode": "en"}\r\n'

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值