我試圖:文件IO與defaultdict
- 負載詞典
- 更新/更改字典
- 保存
- (重複)
問題:我想僅使用1個字典(players_scores) 工作,但defaultdict表達式創建了一個完全獨立的字典。 如何加載,更新並保存到一本字典?
代碼:
from collections import defaultdict#for manipulating dict
players_scores = defaultdict(dict)
import ast #module for removing string from dict once it's called back
a = {}
open_file = open("scores", "w")
open_file.write(str(a))
open_file.close()
open_file2 = open("scores")
open_file2.readlines()
open_file2.seek(0)
i = input("Enter new player's name: ").upper()
players_scores[i]['GOLF'] = 0
players_scores[i]['MON DEAL'] = 0
print()
scores_str = open_file2.read()
players_scores = ast.literal_eval(scores_str)
open_file2.close()
print(players_scores)
除非*有*,否則不要使用'ast.literal_eval'。相反,使用'json'模塊,它可以很好地滿足您的需求。 'json.dump(fileobj)',然後'json.load(fileobj)'(不需要'.read()'或'.write()')。 – 2013-04-26 21:11:35