简体   繁体   English

CSV 文件格式 – 在每第 n 个条目后开始一个新行

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

I am currently trying to organize data collected by a web scraper into a .csv file.我目前正在尝试将网络爬虫收集的数据组织到 .csv 文件中。 The data is collected in a list and then written as csv.数据收集在一个列表中,然后写入 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()

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.然后将分块列表写入 CSV 文件。

writer.writerows(chunks(dataliste, 5))

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM