Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k 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)])

Browse Categories

...