sreevalsan
sreevalsan

Reputation: 33

How to write Dynamic Values of Dictionary into csv python

I have a Dictionary where Keys are static and Values are Dynamic. I want to add those values into CSV file.

Input is given below :-

dictionary=[{
Name: f"{name of the person}",
Age: f"{Age of the person}",
Place:f"{place name}"
}]

Field names are given below

field_name=["Name","Age","Place"]

I want the csv like :

Name age place
A     1   Avc
B     2   Bds
C     3   Vsd
...   .. ....
...   .. ....
...   .. ....

But What I am getting is

Name age place
A     1   Avc
Name age place
B     2   Bds
Name age place
C     3   Vsd
Name age place
...  ..  ....
Name age place
...  ..  ....

My code to operate the csv is shown below.

with open("csv_can.csv","a",newline="") as f:
        writ= csv.DictWriter(f,fieldnames=field_names)
        writ.writeheader()
        writ.writerows(dictionary)

dictionary cointain Key:value pair and field_names contain Keys. This code is running in a while True loop

Upvotes: 2

Views: 540

Answers (2)

Epsi95
Epsi95

Reputation: 9047

You are appending (by using ...th open("csv_can.c...👉"a",...ine=""...) as f:) the header again and again. Just check (if not os.path.isfile("csv_can.csv"):)if the file already exists. If so don't write the header again.

import csv
import os

A = 'A'
place_name = 'B'

dictionary = [{ 'Name': f'{A}', 'Age':f'{1}', 'Place':f'{place_name}'}]

field_names = ['Name', 'Age', 'Place']
with open("csv_can.csv","a",newline="") as f:
    writ= csv.DictWriter(f,fieldnames=field_names)
    if not os.path.isfile("csv_can.csv"):
        writ.writeheader()
    writ.writerows(dictionary)

Upvotes: 2

Tamil Selvan
Tamil Selvan

Reputation: 1749

I am not sure what is your question here, like @epsi95 said, please provide what is your sample and how it needs to be looked.meantime, try this if this can apply to you,

import pandas as pd
yourdict = {'A':'1','B':'2','C':'3'
            }
df = pd.DataFrame(list(yourdict .items()))
df.to_csv('yourcsv.csv')

Upvotes: 0

Related Questions