在将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))
任何建议!你知道吗
您正在编写分隔文本,因此应该使用} 对象,非常适合这个。你知道吗
csv
模块。它正好有一个^{下面是一种使用动态标题列表写出数据的方法:
使用Python熊猫。你知道吗
输出:我的表格.csv你知道吗
| C1 | C2 | C3
0 | 1 | 2 | 3
1 | 4 | 5 | 6个
相关问题 更多 >
编程相关推荐