我的目标是将字典写入文本(以便我不必继续访问数据库),然后将信息保存到文本文件中作为字典。这是我的尝试:如何将字典写入文本,然后将文本读取到python中的字典
要编写字典文本,我用
with open("match_histories.txt", "w") as text_file:
print("match_histories: {}".format(match_histories), file=text_file)
这似乎很好地工作,我的文本文件看起来像:
match_histories: {'28718115': {'matches': [{'matchVersion': '5.13.0.329', ...
我要救这个作为字典,所以我尝试过:
match_histories = {}
f=open('match_histories.txt', 'r')
match_histories= eval(f.read())
但是,当我运行它时,在尝试保存新的dictiona时出错RY。我收到以下错误
Traceback (most recent call last):
File "C:\Python34\Main.py", line 87, in
main()
File "C:\Python34\Main.py", line 82, in main
new_dict = eval(f.read())
File "", line 1
应该如何将我的文本文件中的信息保存为Python中的字典?
编辑:感谢namooth,问题是我的文本文件不是有效的字典格式。我怎么能不把我的字典的名称写入文件?
编辑2:哇,每个人都超级有用!我想我现在已经明白了。
编辑3:我想建议的是,泡菜转储,但我得到这个错误:
Traceback (most recent call last):
File "C:\Python34\Main.py", line 88, in
main()
File "C:\Python34\Main.py", line 79, in main
match_histories=get_match_histories(challenger_Ids)
File "C:\Python34\Main.py", line 47, in get_match_histories
pickle.dump(match_histories, "match_histories.txt")
TypeError: file must have a 'write' attribute
写:
pickle.dump(match_histories, "match_histories.txt")
读:
match_histories = pickle.load("match_histories.txt")
我是否还需要打开文件的行?我如何解决这个错误?
你得到的全部回溯是什么? – Leb