spicyramen spicyramen - 1 month ago 7
Python Question

Remove white space Python writerows

I have the following structure in a dictionary:

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


Im 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 after file, but ideally would like to simplify it.

Answer

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 lists (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())
Comments