简体   繁体   English

如何将字典写入文本,然后在python中读取文本到字典

[英]How to write dictionary to text, then read the text to dictionary in python

My goal is to write a dictionary to text (so that I don't have to keep accessing a database), then save the information in the text file as a dictionary. 我的目标是为文本编写字典(这样我就不必继续访问数据库),然后将信息作为字典保存在文本文件中。 This is what I tried: 这是我尝试的:

To write the dictionary to text, I used 为了将字典写成文字,我用

 with open("match_histories.txt", "w") as text_file:
    print("match_histories: {}".format(match_histories), file=text_file)

This seemed to work nicely and my text file looks like: 这似乎工作得很好,我的文本文件如下所示:

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

I want to save this as a dictionary, so I tried: 我想将其保存为字典,所以我尝试了:

match_histories = {}
f=open('match_histories.txt', 'r')
match_histories= eval(f.read())

However, when I run it, I get an error in trying to save the new dictionary. 但是,当我运行它时,在尝试保存新词典时出现错误。 I get the following error 我收到以下错误

Traceback (most recent call last): 追溯(最近一次通话):

File "C:\\Python34\\Main.py", line 87, in 文件“ C:\\ Python34 \\ Main.py”,第87行,在

main() 主要()

File "C:\\Python34\\Main.py", line 82, in main main中的文件“ C:\\ Python34 \\ Main.py”,第82行

new_dict = eval(f.read()) new_dict = eval(f.read())

File "", line 1 文件“”,第1行

How should I save the information from my text file as a dictionary in Python? 如何在Python中将文本文件中的信息保存为字典?

Edit: Thanks to namooth, the problem was that my text file was not in a valid dictionary format. 编辑:感谢namooth,问题是我的文本文件不是有效的字典格式。 How can I not write the name of my dictionary to the file? 如何不将字典的名称写入文件?

Edit 2: Wow, everyone is super helpful! 编辑2:哇,每个人都超级有帮助! I think I've got it now. 我想我已经知道了。

Edit 3: I tried the pickle dump that was suggested, but i got this error: 编辑3:我尝试了建议的泡菜转储,但出现此错误:

Traceback (most recent call last): 追溯(最近一次通话):

File "C:\\Python34\\Main.py", line 88, in 文件“ C:\\ Python34 \\ Main.py”,第88行,在

main() 主要()

File "C:\\Python34\\Main.py", line 79, in main 主文件中的文件“ C:\\ Python34 \\ Main.py”,行79

match_histories=get_match_histories(challenger_Ids) match_histories = get_match_histories(挑战者ID)

File "C:\\Python34\\Main.py", line 47, in get_match_histories get_match_histories中的文件“ C:\\ Python34 \\ Main.py”,第47行

pickle.dump(match_histories, "match_histories.txt") pickle.dump(match_histories,“ match_histories.txt”)

TypeError: file must have a 'write' attribute TypeError:文件必须具有“写入”属性

write: 写:

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

read: 读:

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

Do I still need a line opening the file? 我还需要一行来打开文件吗? How do I fix this error? 如何解决此错误?

json模块对我来说是完美的,因为pickle产生几乎不可读的内容

You should have a valid dictionary syntax in your text file. 您的文本文件中应该具有有效的字典语法。 The following will work with your loading code: 以下将与您的加载代码一起使用:

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

The issue with your current code is that you're adding a prefix "match_histories: " before the repr of your dictionary. 当前代码的问题是,您要在字典的repr之前添加前缀"match_histories: " Python can't parse that part of the text, so you get an error when you eval it. Python无法解析文本的这一部分,因此在eval文本时会出现错误。

Try just writing the repr of the dictionary by itself: 尝试仅自己编写字典的repr

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

This will work if all of the objects contained at any level in the dictionary have repr s that can be parsed back in properly. 如果字典中任何级别上包含的所有对象都具有可正确解析的repr ,则此方法将起作用。 It won't work if the dictionary contains objects with unhelpful repr s, or if it contains recursive references. 如果字典包含无用的对象,它不会工作repr S,或者如果它包含递归引用。

A better approach is probably to use the pickle modules to save an load your data to a file: 更好的方法可能是使用pickle模块将数据加载保存到文件中:

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

And later: 然后:

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

You could also use the json module if you want the text file to be human readable. 如果您希望文本文件易于阅读,也可以使用json模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM