【发布时间】:2019-10-16 08:51:38
【问题描述】:
我有一个包含多个字典的文件。以下只是文件的一部分。我需要将其转换为 csv 文件并最终将其加载到数据库中。我在将其转换为 csv 时遇到问题。
{"transaction_type": "new", "policynum": 4994949}
{"transaction_type": "renewal", "policynum": 3848848}
{"transaction_type": "cancel", "policynum": 49494949, "cancel_table":
[{"cancel_cd": "AU", "cancel_type": "online"}, {"cancel_cd": "AA", "cancel_type": "online"}]}
我已尝试实现以下代码,但取消表键未正确解析到 csv 文件中。
import ast
import csv
with open('***\\Python\\test', 'r') as in_f, open('***\\Python\\test.csv', 'w') as out_f:
data = in_f.readlines()
writer = csv.DictWriter(out_f, fieldnames=['transaction_type', 'policynum', 'cancel_table'], extrasaction='ignore')
writer.writeheader() # For writing header
for row in data:
dict_row = ast.literal_eval(row) # because row has a dict string
writer.writerow(dict_row)
下面是我得到的结果,取消表键未正确解析到 csv 文件中。我需要帮助将 cancel_type 和不同的 cancel_cd 作为单独的列。或者 cancel_cd 用逗号分隔符连接在一列中(只是一个想法)。抱歉,如果这是一个加载的问题。
transaction_type,policynum,cancel_table
new,4994949,
old,3848848,
cancel,49494949,"[{'cancel_type': 'online','cancel_cd': 'OL'}, 'cancel_type': 'Online','cancel_cd': 'BR'},{'cancel_type': 'online','cancel_cd': 'AU', }]"
【问题讨论】:
标签: python-3.x