Reputation: 1832
I have list like the one below,
lista=["a","b","c","\n","d","e","f","\n","g","h","i","\n"]
Can some one please advise how I make csv module to write this so that every "\n" in the list is counted as a line break? To make it simpler the csv should look like this,
a,b,c
d,e,f
g,h,i
Please let me know if the question is not clear, I will make changes as required.
Upvotes: 0
Views: 71
Reputation: 369134
import csv
import sys
def rows(lst):
it = iter(lst)
while True:
row = list(iter(it.next, '\n')) # it.__next__ in Python 3.x
if not row:
break
yield row
lista = ["a","b","c","\n","d","e","f","\n","g","h","i","\n"]
writer = csv.writer(sys.stdout) # Replace sys.stdout with file object
writer.writerows(rows(lista))
Upvotes: 1
Reputation: 249293
You don't really need the CSV module:
for s in ','.join(lista).split('\n'):
print(s.strip(','), '\n')
This gives:
a,b,c
d,e,f
g,h,i
Upvotes: 0