这是我到目前为止所拥有的。
from os import path
dirt = path.dirname(__file__)
#########################################################
def save(hs):
f = open(path.join(dirt, "testscores.txt"), "w")
for i in range(3):
f.write(str(hs[i]))
if i != len(hs):
f.write("\n")
f.close()
def load():
global hs
f = open(path.join(dirt, "testscores.txt"), "r")
hs = f.read().splitlines()
f.close()
#########################################################
try:
load()
except:
hs = [5000, 2000, 300]
hst = int(input("score?"))
hs.append(hst)
print(hs)
hs.sort(key = int, reverse = True)
hs = hs[:3]
save(hs)
我一直遇到列表索引超出范围,sort()无法正常工作或临时高分被写入4次的情况。
答案 0 :(得分:0)
列表索引超出范围
说您的"testscores.txt"
为空。调用load()
时,您会得到hs = []
。然后输入1个新分数,您得到hs = [100]
。然后调用save()
,它会尝试获取显然超出范围的hs[1]
和hs[2]
。
尝试使用with
statement,而不是open
和close
。也不要使用global hs
,而是返回hs
def load():
with open("file path", "r") as f:
hs = f.read().splitlines()
return hs
try:
hs = load()
对于save()
,为避免索引超出范围,您要检查输入列表的长度。 hs = hs[:3]
是不必要的。理想情况下,该功能应该能够处理所有输入,因此让该功能进行检查。
def save(hs):
# How many scores are we saving
# hm_score equates to 3 if more than 3 scores are in the list
# equates to 0, 1, or 2 if less than 3 scores are in the list
hm_score = min(len(hs), 3)
# Trim hs to 3 if more than 3 scores are in the list
hs = hs[:hm_score]
with open("file path", 'w') as f:
# Join all the scores in hs with a line break
text = '\n'.join(hs)
f.write(text)
# File is closed automatically outside the with statement
sort()不起作用
应该没错。也可以考虑将sort()
放在save()
内,以使环境更清洁。