2015-07-13 418 views
0

我的目标是将字典写入文本(以便我不必继续访问数据库),然后将信息保存到文本文件中作为字典。这是我的尝试:如何将字典写入文本,然后将文本读取到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") 

我是否还需要打开文件的行?我如何解决这个错误?

+0

你得到的全部回溯是什么? – Leb

回答

0

与您当前密码的问题是,你在你的字典的repr前添加一个前缀"match_histories: "。 Python无法解析文本的那一部分,所以当你遇到错误时它会出现错误。

尽量只用本身编写的字典repr

with open("match_histories.txt", "w") as text_file: 
    print(repr(history), file=text_file) 

如果所有包含在字典中的任何级别上的对象有repr s表示可以解析回正常这将工作。如果字典中包含的对象具有无用的repr或者它包含递归引用,它将不起作用。

一个更好的办法可能是使用pickle模块保存你的数据在加载到一个文件:

pickle.dump(history, "match_histories.txt") 

及更高版本:

new_dict = pickle.load("match_histories.txt") 

你也可以,如果你使用json模块希望文本文件是人类可读的。

0

你应该在你的文本文件的有效字典语法。下面将与您加载代码的工作:

{'match_histories': {'28718115': {'matches': [{'matchVersion': '5.13.0.329', ...}

+0

谢谢!那工作。 match_histories是变量名称(在我的代码中称为new_dict);也许这不应该包含在文本文件中?那么我应该如何改变我的“写入”部分,使其不包含我用于字典的名称? – Mark

+0

我会用'text_file.write(str(history))',其中history是你的字典。 – namooh