[英]Write list of dictionaries to CSV from file
我想將字典列表從文件寫入新的CSV文件。 這是我的代碼。
import csv
myfile = open(filename, 'r')
tocsv = myfile.read()
myfile.close()
keys = tocsv[0].keys()
with open(filename.join('.csv'), 'w+') as outputfile:
dictwriter = csv.DictWriter(outputfile, keys)
dictwriter.writeheader()
dictwriter.writerows(tocsv)
但是,在第7行中, keys = tocsv[0].keys()
,python將tocsv
解釋為字符串,這使我無法使用keys()
函數。 而且我不能在這里使用eval
,因為它是字典列表,所以我遇到了麻煩。 歡迎任何幫助。
提前致謝。
嘗試json.load()
,查看字典列表是否為格式正確的JSON:
import json
with open(filename, 'r') as myfile:
tocsv = json.load(myfile)
keys = tocsv[0].keys()
...
否則,請嘗試使用ast
模塊來評估文字:
import ast
with open(filename, 'r') as myfile:
tocsv = ast.literal_eval(myfile.read())
keys = tocsv[0].keys()
...
注意:字典未排序,因此鍵的順序可能與原始字典的順序不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.