I am trying to split my list of dict into multiple csv's but it's not working here is my code for this:
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
}]
This is my list and here the code to the splitting
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)
But it doesn't work.
CodePudding user response:
So, what I understand from your question is that you want each dictionary content to be written in a separate CSV file. here is a code that does that:
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])
Output: 5 different CSV files batch1.csv, batch2.csv,..., batch5.csv, and each contain the content of the dictionary at the respective position in the fruits list.
CodePudding user response:
Refactor your code to open the file first, write the header, then write the rows in a loop. What you have is writing the header before each row.
