【发布时间】:2019-07-20 08:52:31
【问题描述】:
我有一个列表列表,每个子列表中包含不同数量的字符串:
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