将多个列表写入csv Python

时间:2017-10-22 00:00:37

标签: python list csv

我试图编写一个函数,将多个列表写入单个csv文件,我能够获得要写的列标题,但不能写入任何数据。我的数据列在类似于[92,3801,2,22,4]的列表中,第二个是[3.0,2,23,5],我正在寻找相关的指导。谢谢!

import csv
def export_results(number_of_words_sentence,mean_word_per_sentence):
    with open("assignment_7_results.csv", "w", newline="") as Assignment_7_results:
        writer = csv.writer(Assignment_7_results)
        writer.writerow(["Number of Words", "Words/Sentence"])
    # Our .csv file will have two columns, one for the dict keys and one for the dict values
        writer.writerows(number_of_words_sentence)
        writer.writerows(mean_words_per_sentence)

2 个答案:

答案 0 :(得分:1)

顾名思义,writerows写行而不是列。此外,您的列表大小不同,因此您需要做一些事情来解决这个问题。处理此类事情的标准方法是使用itertools.zip_longest

from itertools import zip_longest # izip_longest in python2.x

with open("assignment_7_results.csv", "w") as f:
    w = csv.writer(f)
    w.writerow(["Number of Words", "Words/Sentence"])
    for x, y in zip_longest(number_of_words_sentence, mean_word_per_sentence):
        w.writerow([x, y])

答案 1 :(得分:0)

尝试使用此命令将数据存储在具有多个不同长度列表的csv文件中。在这里,我尝试使用与A和B相同的标题作为列表名称。

import pandas as pd

A = ['Apple', 'Dog']

B = ['Cat', 'OWL', 'PEACOCK']

dict_1 = {'A': A, 'B': B}

df = pd.DataFrame.from_dict(dict_1, orient='index')

dt = df.transpose()

dt.to_csv('myfile.csv', index=False, header=True,  encoding='utf-8')