[英]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.