0 votes
1 view
in Python by (8.4k points)

I have a list in Python 3. I want to split a list [1,2,3,4,5,6,7,8] to [1,2,3,4] in one row and [5,6,7,8] the other. I am currently using this to write to CSV however I am doing the split manually and there will be a blank cell after it writes not sure how to get rid of it that's another problem also.

outfile = open('list.csv','w')

out = csv.writer(outfile)

out.writerows(map(lambda x: [x],list))

outfile.close()

1 Answer

0 votes
by (16.8k points)

This might work: 

outfile = open('list.csv', 'w', newline='')

out = csv.writer(outfile)

out.writerows([list[i:i+4] for i in range(0, len(list), 4)])

outfile.close()

Or simply use, with open:

with open('list.csv', 'w', newline='') as outfile:

    out = csv.writer(outfile)

    out.writerows([list[i:i+4] for i in range(0, len(list), 4)])

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...