如何将包含字典列表的文件读入python?

时间:2016-02-21 16:58:09

标签: python dictionary

我创建了一个包含我正在使用的词典列表的文件。不幸的是,我不知道如何以相同的格式将该文件重新导入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中 - 即字典列表吗?

2 个答案:

答案 0 :(得分:4)

您错误地使用了json.dump()。您应该直接将d传递给它,而不是json.dumps(d)的输出。完成后,您可以使用json.load()检索数据。

with open('list_of_dics.txt', 'r') as infile:
    d = json.load(infile)

答案 1 :(得分:2)

使用

json.dumps(d)

你在字符串中有(JSON-)编码列表d(你将其分配给误导性地称为jsonarray的变量)。

使用

json.dump(jsonarray, outfile)

您对字符串进行了JSON编码,并将结果写入outfile

现在(不必要地)在文件list_of_dics.txtlist_of_dics.json中进行了双重JSON编码。

干净地从那里取回它(不使用manual string manipulation),你必须解码它两次:

import json

with open('list_of_dics.json', 'r') as infile:
    recovered_d = json.loads(json.load(infile))