python csv writer不需要时添加引号 [英] python csv writer is adding quotes when not needed
问题描述
我遇到问题使用csv写入json对象到文件,json对象似乎有多个双引号,因此导致json对象变得无效,这里是结果:
{user.CustomAttribute.ISOLanguageCode:en,user.Email:emzy1786@googlemail.com
我想要的是
{user.CustomAttribute.ISOLanguageCode:en,user.Email:emzy1786@googlemail.com}
pre>
这里是我如何打开文件,也许有一个参数,我可以通过防止这种情况发生?
file = csv.writer(open(localResultPath +.txt,'ab'),delimiter ='|')
这里是我写入文件的方式,最后一个append将json作为字符串
list.append(pk)
list.append(email)
list.append(json)
file.writerow(list)
解决方案用
quoting = csv.QUOTE_NONE
引用,并将quotechar
添加到空字符串:file = csv.writer(open(localResultPath +.txt,'ab'),
delimiter ='|',quoting = csv。 QUOTE_NONE,quotechar ='')
即使使用
csv.QUOTE_NONE
csv.writer()
仍然会引用quotechar
空字符串,如果存在的值。默认的引号字符是<code>和JSON值都是这些。
演示:
>>> 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\\\
'
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 setquotechar
to the empty string:file = csv.writer(open(localResultPath + ".txt",'ab'), delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
Even with
csv.QUOTE_NONE
thecsv.writer()
will still want to quote thequotechar
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'
这篇关于python csv writer不需要时添加引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!