我是一个python noob来解决这个问题我正在使用OOP方法编写这些函数只是一个FYI。我的save_roster函数正常工作,它将所有字典播放器名单保存到我的文本文件'名单中。我通过查看文本文件确认这一切确认了这一点。现在,当我去load_roster函数时,它只加载第一个键和值,而其余的都没有,我无法找出原因。关于我如何加载整个字典或我做错了什么的任何帮助将不胜感激。
def save_roster(player_roster):
print("Saving data...")
file = open("roster.txt", "wt")
import csv
w = csv.writer(open("roster.txt", "w"))
for key, val in player_roster.items():
w.writerow([key, val])
print("Data saved.")
file.close()
def load_roster(player_roster):
print("Loading data...")
import csv
file = open("roster.txt", "rt")
for key, val in csv.reader(file):
player_roster[key] = eval(val)
file.close()
print("Data Loaded Successfully.")
return (player_roster)
答案 0 :(得分:0)
您的return (player_roster)
语句位于for
循环内,这意味着它只在返回之前读取第一行。您需要将语句放在循环之外,如下所示:
def load_roster(player_roster):
print("Loading data...")
import csv
file = open("roster.txt", "rt")
for key, val in csv.reader(file):
player_roster[key] = eval(val)
file.close()
print("Data Loaded Successfully.")
return (player_roster)