在将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))
任何建议!
答案 0 :(得分:4)
这是一种使用动态标题列表写出数据的方法:
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")
答案 1 :(得分:2)
您正在编写分隔文本,因此您应该使用csv
模块。它碰巧有一个DictWriter
对象,非常适合这种情况。
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)
答案 2 :(得分:0)
使用python pandas。
import pandas as pd
tableA = pd.DataFrame([[1,2,3],[4,5,6]], columns=["C1","C2","C3"])
tableA.to_csv("mytables.csv",sep="|")
OUTPUT:mytables.csv
| C1 | C2 | C3
0 | 1 | 2 | 3
1 | 4 | 5 | 6