0

I have a dictionary like this. I want to write the data inside to csv file but I will run my code over and over again. How can I make it write headers only once? How can I remove the spaces between the lines?

My code

import csv

dl = {7: {'id': 11, 'name': 'Abc', 'age': 35},
      25: {'id': 28, 'name': 'refd', 'age': 88},
      15: {'id': 45, 'name': 'dfgd', 'age': 20}}
id_list = [7, 25, 15]

def to_csv(data):
    fieldnames = ['id', 'name', 'age']
    with open('data.csv', 'a+') as f:
        dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
        dict_writer.writeheader()
        dict_writer.writerow(data)

for i in id_list:
    to_csv(dl[i])

for empty lines solution is

with open('data.csv', newline='', 'a+') as f:

first rub output:

first rub output

second run output:

second run output

2 Answers 2

2

How about passing a value to your function to indicate whether or not the headers should be written? Something like this:

def to_csv(data, writeheader):
    fieldnames = ['id', 'name', 'age']
    with open('data.csv', 'a+') as f:
        dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
        if writeheader:
            dict_writer.writeheader()
        dict_writer.writerow(data)
id_list = [7,25,15]
for i in id_list:
    to_csv(dl[i], i==id_list[0])
Sign up to request clarification or add additional context in comments.

3 Comments

My fault. It isn't like 1-2-3 actually. Ids are like 5-9-50-2-715. I shared it this way as an example. I will fix it.
Edited to suit the changed question
Same logic. Right. :D I think this will work for me. Any idea about empty rows?
0
dict_writer.writeheader()  # write the header in your file
dict_writer.writerow(data)  # write the data in your file

So instead of looping these two lines, you should only run writeheader once and run the writerow function multiple times.

I will let you figure out the actual implementation

2 Comments

But i run this code multiple times. How i can run writeheader once? I should check if my csv file has header if it has then dont run writeheader. But couldn't do it.
Answer from @arthur.king would work, but I personally think this is not a good idea to run the to_csv function every time you loop the row. A better approach would be to process all your data in to_csv function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.