我有一个包含Python字典的txt文件,并以以下方式打开它:
with open('file') as f:
test = list(f)当我看测试时,结果是一个元素的列表。第一个元素是字典的一个字符串(其中还包含其他字典),因此它看起来如下:
["ID": 1, date: "2016-01-01", "A": {name: "Steve", id: "534", players:{last: "Smith", first: "Joe", job: "IT"}}是否有任何方法可以将其存储为字典,而不必找到一种方法来确定不同键和相应值开始/结束的字符的索引?或者是否有可能以将数据识别为字典的方式在文件中读取?
发布于 2016-02-01 05:30:20
您可以使用json模块
用于编写
import json
data = ["ID": 1, date: "2016-01-01", "A": {name: "Steve", id: "534", players:{last: "Smith", first: "Joe", job: "IT"}}
with open("out.json", "w") as f:
json.dump(data)用于阅读
import json
with open("out.json", "w") as f:
data = json.load(f)
print datahttps://stackoverflow.com/questions/35123449
复制相似问题