我的目標是將字典寫入文本(以便我不必繼續訪問數據庫),然後將信息保存到文本文件中作爲字典。這是我的嘗試:如何將字典寫入文本,然後將文本讀取到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