我的测验挑战中遇到问题。测验结束后,应将玩家的分数和姓名发送到dat文件。问题是当我尝试打开保存的文件时,只看到一个name:score记录。哪里有错? 整个代码:code
在代码中,add_score def应该将得分保存到列表中,在整个代码之后,我想打开它。有人可以帮我吗?
import os
import numpy as np
import matplotlib.pyplot as mpplot
import matplotlib.image as mpimg
images = []
path = "../path/to/img/folder/"
for root, _, files in os.walk(path):
current_directory_path = os.path.abspath(root)
for f in files:
name, ext = os.path.splitext(f)
if ext == ".png":
current_image_path = os.path.join(current_directory_path, f)
current_image = mpimg.imread(current_image_path)
images.append(current_image)
for img in images:
print img.shape
然后当我尝试打开分数时:
def add_score(name,score):
"""
Dodaje wynik do osobnego pliku .
:param name:
:param score:
:return:
"""
my_list = []
scores = (name,score)
my_list.append(scores)
with open("score_games.dat", "ab") as f:
pickle.dump(my_list, f)
f.close()
答案 0 :(得分:0)
这里的问题是,每次调用add_score()
时,您都会创建一个带有单个条目的全新列表,然后将其腌制。因此,当您加载泡菜文件时,您将获得最后一个仅包含一个条目的泡菜列表。
add_score()
应该首先加载已腌制的列表,然后将分数添加到其中,然后再将其腌制。
def add_score(name,score):
"""
Dodaje wynik do osobnego pliku .
:param name:
:param score:
:return:
"""
try:
# Load the existing list of scores first, if it exists
with open("score_games.dat", "rb") as f:
my_list = pickle.load(f)
except FileNotFoundError:
my_list = []
scores = (name,score)
my_list.append(scores)
with open("score_games.dat", "ab") as f:
pickle.dump(my_list, f)
f.close()