简体   繁体   中英

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:

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:

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.

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. You need to provide some sort of escape character, or allow quoting (allowing quoting with QUOTE_MINIMAL is the default).

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.

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:

# 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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