aabujamra
aabujamra

Reputation: 4636

csv.writer inserting comma between each character

I'm using the following code:

plugara=['CNPJ', 56631781000177, 21498104000148, 3914296000144, 28186370000184]
plugara=map(str,plugara)

with open(result.csv, 'w') as f:
            wr = csv.writer(f,dialect='excel')
            wr.writerows(plugara)

The result I'm getting is putting a comma between each character and is breaking into a different column:

enter image description here

I would like it to be without those commas like this:

enter image description here

Any ideas?

Upvotes: 0

Views: 1027

Answers (1)

Blckknght
Blckknght

Reputation: 104842

The writerows method that you're calling expects its argument to be an iterable containing rows. Each row should be iterable itself, with its values being the items in the row. In your case, the values are strings, which can be iterated upon to give their characters. Unfortunately, that's not what you intended!

Exactly how to fix this issue depends on what you want the output to be.

If you want your output to consist of a single row, then just change your call to writerow to instead of writerows (note the plural). The writerow method will only write a single row out, rather than trying to write several of them at once.

On the other hand, if you want many rows, with just one item in each one (forming a single column), then you'll need to transform your data a little bit. Rather than directly passing in your list of strings, you need to produce an iterable of rows with one item in them (perhaps 1-tuples). Try something like this:

wr.writerows((item,) for item in plugara)

This call uses a generator expression to transform each string from plugara into a 1-tuple containing the string. This should produce the output you want.

Upvotes: 1

Related Questions