将列表列表中的每个子列表写入单独的CSV

问题描述 投票:0回答:1

我有一个列表列表,每个子列表中包含不同数量的字符串:

tq_list = [['The mysterious diary records the voice.', 'Italy is my favorite country', 'I am happy to take your donation', 'Any amount will be greatly appreciated.'], ['I am counting my calories, yet I really want dessert.', 'Cats are good pets, for they are clean and are not noisy.'], ['We have a lot of rain in June.']]

我想为每个子列表创建一个新的CSV文件。到目前为止,我所有的方法都是使用以下代码将每个子列表作为一行输出到同一CSV文件中:

name_list = ["sublist1","sublist2","sublist3"]

with open("{}.csv".format(*name_list), "w", newline="") as f:
    writer = csv.writer(f)
    for row in tq_list:
        writer.writerow(row)

这将创建一个名为“sublist1.csv”的CSV文件。


我玩弄了以下代码:

name_list = ["sublist1","sublist2","sublist3"]

for row in tq_list:
    with open("{}.csv".format(*name_list), "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(row)

这也仅输出名为“sublist1.csv”的单个CSV文件,但仅包含最后一个子列表中的值。我觉得这是朝着正确方向迈出的一步,但显然还不是很好。

python-3.x csv export-to-csv nested-lists sublist
1个回答
0
投票

你的代码中*中的"{}.csv".format(*name_list)实际上是这样做的:它解压缩name_list中的元素以传递给函数(在本例中为format)。这意味着format(*name_list)相当于format("sublist1", "sublist2", "sublist3")。由于您的字符串中只有一个{},因此除"sublist1"之外的所有格式参数都将被丢弃。

你可能想做这样的事情:

for index, row in enumerate(tq_list):
    with open("{}.csv".format(name_list[index]), "w", newline="") as f:
        ...

enumerate返回一个计数索引以及它迭代的每个元素,以便您可以跟踪已经存在的元素数量。这样你每次都可以写入不同的文件。您还可以使用zip,这是另一个可以在Python文档中查找的便捷函数。

© www.soinside.com 2019 - 2024. All rights reserved.