用python将dict列表写入文件

2024-04-20 09:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在将db输出写入文件时,我在动态映射字典值方面遇到了问题。 场景:

new_list = [{'Table':'A', 'Column':'C1', 'DataType':'int'},
        {'Table':'A', 'Column':'C2', 'DataType':'varchar'},
        {'Table':'A', 'Column':'C2', 'DataType':'numeric'}
       ]
# I want to write the data into a file.
Table|Column|DataType
A|C1|int
A|C2|varchar
A|C3|numeric

我正在努力做到下面这样。你知道吗

header = []
with open('my_log.log', 'w',encoding='utf-8') as log:
   for n in new_list:
      for i in n.keys():
        header.append(i)
   log.write("|".join(set(header)))
   log.write("\n")
   for data in new_list:
      # don't want to hard code the keys like below
      log.write("{Table}|{Column}|{DataType} \n".format(**data))
      # need to do something so that I dont have to hard code the keys as it  is dynamic in nature
      # and also my file output should match with the header generated in the previous line
      log.write("{???}".format(**data))

任何建议!你知道吗


Tags: thetoinlognewfordatatable
3条回答

您正在编写分隔文本,因此应该使用csv模块。它正好有一个^{}对象,非常适合这个。你知道吗

import csv

new_list = [{'Table':'A', 'Column':'C1', 'DataType':'int'},
    {'Table':'A', 'Column':'C2', 'DataType':'varchar'},
    {'Table':'A', 'Column':'C2', 'DataType':'numeric'}
   ]

with open("my_log.log", "wb") as f:
    writer = csv.DictWriter(f,
                            fieldnames=["Table", "Column", "DataType"],
                            delimiter="|")
    writer.writerows(new_list)

下面是一种使用动态标题列表写出数据的方法:

new_list = [{'Table':'A', 'Column':'C1', 'DataType':'int'},
        {'Table':'A', 'Column':'C2', 'DataType':'varchar'},
        {'Table':'A', 'Column':'C2', 'DataType':'numeric'}
       ]

header = new_list[0].keys()

with open('my_log.log', 'w') as log:
   log.write("|".join(header))
   log.write("\n")
   for data in new_list:
      log.write("|".join(data[h] for h in header))
      log.write("\n")

使用Python熊猫。你知道吗

import pandas as pd
tableA = pd.DataFrame([[1,2,3],[4,5,6]], columns=["C1","C2","C3"])
tableA.to_csv("mytables.csv",sep="|")

输出:我的表格.csv你知道吗

| C1 | C2 | C3

0 | 1 | 2 | 3

1 | 4 | 5 | 6个

相关问题 更多 >