拆分字典并将其保存到多个 CSV 中

Splitting a Dictonary and saving it into multiple CSV's

我正在尝试将我的 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)

但是不行。

重构您的代码以先打开文件,写入 header,然后循环写入行。你所拥有的是在每一行之前写 header。

所以,我从你的问题中了解到,你希望每个词典内容都写在一个单独的 CSV 文件中。这是执行此操作的代码:

import sys
import os
import 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 dict_ in fruits:
   index +=1
   for k,v in dict_.items():
      #print(dict_)
      file_name = f"batch{index}.csv"
      with open("./CSV/" + f"batch{index}.csv", 'a', newline='') as output_file:
            dict_writer = csv.writer(output_file)
            dict_writer.writerow([k,v])

输出:5 个不同的 CSV 文件 batch1.csv、batch2.csv、...、batch5.csv,每个文件都包含水果列表中相应位置的词典内容。