简体   繁体   English

删除空白Python writerows

[英]Remove white space Python writerows

I have the following structure in a dictionary: 我在字典中具有以下结构:

 self._results = {'key1':'1,2,3','key2':'5,6,7'}

I'm using csv writerows() to write the records from the dictionary into a file: 我正在使用csv writerows()将字典中的记录写入文件:

filewriter = csv.writer(
          csvfile,
          quoting=csv.QUOTE_NONE,
          delimiter=',',
          quotechar='',
          escapechar=' ')
      filewriter.writerows(self._results.items())

Unfortunately I get the following: 不幸的是,我得到以下信息:

key1,1 ,2 ,3
key2,4 ,5 ,6

If I remove escapechar or change it to '' I get: 如果我删除escapechar或将其更改为''我得到:

Error: need to escape, but no escapechar set

Any suggestions? 有什么建议么?

I can remove whitespaces by manipulating the CSV file afterwards, but ideally I would like to do all the text manipulation in one place. 之后可以通过处理CSV文件来删除空格,但理想情况下,我希望将所有文本处理都放在一个位置。

You disabled quoting. 您禁用了报价。 So without an escape character, it can't output the commas; 因此,如果没有转义字符,它将无法输出逗号。 they'd be mistaken for field separators in the CSV format. 他们会误认为CSV格式的字段分隔符。 You need to provide some sort of escape character, or allow quoting (allowing quoting with QUOTE_MINIMAL is the default). 您需要提供某种转义符,或者允许使用引号(默认情况下允许使用QUOTE_MINIMAL进行引号)。

If your goal was to have 1 , 2 and 3 be separate fields in the result, you shouldn't be storing them as a pre-comma separated string in the dict , because that's csv 's job, and trying to do its job for it just means fighting csv and risking logic errors that make it impossible to round trip the data correctly. 如果你的目标是有123是在结果不同的领域,你不应该将其存储作为预逗号的分隔字符串dict ,因为这是csv的工作,并试图完成其工作的这仅意味着与csv对抗,并冒使无法正确往返数据的逻辑错误的风险。

If they're a single logical field, allow quoting. 如果它们是单个逻辑字段,则允许引用。 If they're more than one field, build the dict as a dict of list s ( defaultdict(list) is helpful if the values are being built piecemeal), then output a raw sequence, not partially preformatted text: 如果它们不止一个字段,则将dict构建为listdict (如果零散构建值,则defaultdict(list)很有用),然后输出原始序列,而不是部分预格式化的文本:

# Define values as lists, not strings
self._results = {'key1':[1,2,3],'key2':[5,6,7]}

# Wrap k in list and concatenate v to make four item list
filewriter.writerows([k] + v for k, v in self._results.items())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM