[英]How can I read a file that contains a list of dictionaries into python?
我創建了一個文件,其中包含我正在使用的詞典列表。 不幸的是,我不確定如何以相同的格式將該文件重新導入python。
我最初將文件寫為JSON和文本形式,如下所示:
d = list_of_dics
jsonarray = json.dumps(d)
with open('list_of_dics.txt', 'w') as outfile:
json.dump(jsonarray, outfile)
with open('list_of_dics.json', 'w') as outfile:
json.dump(jsonarray, outfile)
誰能提出一種以相同格式(即字典列表)將它們重新導入python的方法嗎?
您使用的json.dump()
錯誤。 您應該直接將d
傳遞給它,而不是json.dumps(d)
的輸出。 完成后,您可以使用json.load()
檢索數據。
with open('list_of_dics.txt', 'r') as infile:
d = json.load(infile)
用
json.dumps(d)
您已經(JSON)編碼了一個字符串列表d
(將其分配給一個誤導性的變量jsonarray
)。
用
json.dump(jsonarray, outfile)
您已經對該字符串進行 JSON編碼,並將結果寫入outfile
。
因此,現在(不必要)在文件list_of_dics.txt
和list_of_dics.json
對它進行了JSON雙重編碼。
要從那里干凈地取回它(不求助於手動字符串操作 ),您必須對其解碼兩次:
import json
with open('list_of_dics.json', 'r') as infile:
recovered_d = json.loads(json.load(infile))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.