CSV file formatting – start a new row after every nth entry

50 views Asked by At

I am currently trying to organize data collected by a web scraper into a .csv file. The data is collected in a list and then written as csv.

My problem is that the program is writing the data into a single row in the file.

How can I tell the program to start a new row after for example every fifth entry?

Here is what my code looks like right now:

import csv

csvFile = open('practive.csv', 'w+')

try:
    writer = csv.writer(csvFile, delimiter=',')
    writer.writerow(('kaufpreis', 'ort', 'wohnfläche','zimmer', 'company'))
    writer.writerows([dataliste])
finally:
    csvFile.close()
2

There are 2 answers

0
Barmar On

Split your list into chunks of 5 elements, using one of the techniques in How do you split a list into evenly sized chunks?.

Then write the chunked list to the CSV file.

writer.writerows(chunks(dataliste, 5))
0
deepak sen On

it depends on how you are giving data to the writer

import csv
csvFile = open('practive.csv', 'w+')
dataliste = [[1,2,3,4,5], [11,22,33,44,55]]
try:
   writer = csv.writer(csvFile, delimiter=',')
   writer.writerow(('kaufpreis', 'ort', 
   'wohnfläche','zimmer', 'company'))
   writer.writerows(data for data in dataliste)
finally:
   csvFile.close()