![](/img/trans.png)
[英]I'm trying to print a number of lines of a .txt file using a for loop. It's always missing the last three lines
[英]I'm trying to save the top three highscores to a txt file on seperate lines
到目前为止,这就是我所拥有的。
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次的问题。
列表索引超出范围
说您的"testscores.txt"
为空。 调用load()
,得到hs = []
。 然后输入1个新分数,您将得到hs = [100]
。 然后调用save()
,并尝试获取明显超出范围的hs[1]
和hs[2]
。
代替open
和close
,请尝试使用with
语句 。 也不要使用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()
,以使事情更清洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.