简体   繁体   English

Python:将多个列表写入csv中的多行

[英]Python: write multiple lists to multiple rows in csv

At the moment, I know how to write a list to one row in csv, but when there're multiple rows, they are still written in one row. 目前,我知道如何将列表写到csv的一行中,但是当有多行时,它们仍然写在一行中。 What I would like to do is write the first list in the first row of csv, and the second list to the second row. 我想做的是将第一个列表写到csv的第一行中,然后将第二个列表写到第二行。

Code: 码:

for i in range(10):
    final=[i*1, i*2, i*3]
    with open ('0514test.csv', 'a') as file:
        file.write(','.join(str(i) for i in kk))

You may want to add linebreak to every ending of row. 您可能要在行的每个结尾处添加换行符。 You can do so by typing for example: 您可以通过键入以下内容来执行此操作:

file.write('\n')

The csv module from standard library provides objects to read and write CSV files. 标准库中的csv模块提供了读取和写入CSV文件的对象。 In your case, you could do: 就您而言,您可以执行以下操作:

import csv
for i in range(10):
    final = [i*1, i*2, i*3]
    with open("0514test.csv", "a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(final)

Using this module is often safer in real life situations because it takes care of all the CSV machinery (adding delimiters like " or ', managing the cases in which your separator is also present in your data etc.) 在现实生活中使用此模块通常会更安全,因为它会处理所有CSV机制(添加“或”之类的分隔符,管理在数据中还存在分隔符的情况等)。

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

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