简体   繁体   English

如何将字典的动态值写入 csv python

[英]How to write Dynamic Values of Dictionary into csv python

I have a Dictionary where Keys are static and Values are Dynamic .我有一个字典,其中键是 static 和值是 Dynamic I want to add those values into CSV file.我想将这些值添加到CSV文件中。

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:我想要 csv 像:

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.我操作 csv 的代码如下所示。

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.字典包含 Key:value 对和 field_names 包含键。 This code is running in a while True loop此代码在while True循环中运行

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.您正在附加(通过使用...th open("csv_can.c..."a",...ine=""...) as f: ) header 一次又一次。只需检查( if not os.path.isfile("csv_can.csv"): ) 如果文件已经存在。如果是这样,请不要再次写入 header。

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)

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,我不确定您的问题是什么,就像@epsis95 说的那样,请提供您的样品是什么以及需要如何查看。同时,如果这适用于您,请尝试这个,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM