【发布时间】:2022-01-20 15:42:17
【问题描述】:
我正在尝试将我的 dict 列表拆分为多个 csv,但它在这里不起作用是我的代码:
fruits = [ ##items
{"item": "apple",
"quantity": 5,
"price": 0.95},
{
"item": "orange",
"quantity": 7,
"price": 0.99
},
{
"item": "orange",
"quantity": 7,
"price": 0.99
},
{
"item": "orange",
"quantity": 7,
"price": 0.99
},
{
"item": "orange",
"quantity": 7,
"price": 0.99
}]
这是我的清单,这里是拆分的代码
keys = fruits[0].keys()
try:
os.mkdir("./CSV")
except OSError as e:
print("Directory exists")
index = 0
for key in fruits:
index += 1
if index == 4:
file_name = f"batch{x}.csv"
with open("./CSV/" + f"batch{x}.csv", 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(fruits)
但它不起作用。
【问题讨论】:
-
您希望列表中的每个字典都是单独的 csv 文件还是存在某些条件?
-
您的字典列表包含语法错误。但是您希望各个 csv 文件包含什么?
-
是的,我想将每个字典拆分成一个 csv 文件