【发布时间】:2018-04-17 04:31:30
【问题描述】:
我正在将字典写入文件以保存存储在其中的数据。当我读取文件并尝试将其转换回来时,它会转换为列表。我添加了 print(type()) 以查看它进入文件的类型以及它的输出时间。
import ast
f = open("testfile.txt", "a+")
print (type(dic1))
f.write(str(dic1.items()) + "\n")
f.close()
这是我将它写入文件
([('people', '1'), ('date', '01/01/1970'), ('t0', 'epoch'), ('time', '0'), ('p0', 'Tim Berners-Lee'), ('memory', 'This is the day time was created')])
这是书面文件中的样子。
loadDict = ast.literal_eval(x)
print (type(loadDict))
这是尝试转换回字典时的代码
【问题讨论】:
-
要将字典写入文件,使用
json.dump和json.load会更容易
标签: string python-3.x dictionary abstract-syntax-tree