我正在嘗試將我的 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)
但它不起作用。
uj5u.com熱心網友回復:
所以,我從你的問題中了解到,你希望每個字典內容都寫在一個單獨的 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,每個檔案都包含水果串列中相應位置的字典內容。
uj5u.com熱心網友回復:
重構代碼以首先打開檔案,寫入標題,然后回圈寫入行。你所擁有的是在每一行之前寫標題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417010.html
標籤:
上一篇:zsh變數替換修改周圍的字串
