我正在为一个学校的项目写一个骰子游戏,除了一件事情,我试图将一个列表写到一个文本文件中,并且在其中充满了空白。放在列表中第一项的前面,我只是弄不明白为什么会发生这种情况。(您需要像下面的文本一样设置“最高分”文件。)
最高分文件:
Bobby
67
Gabby
78
Mark
87
James
67
Mike
34
代码中有此问题的部分:
winnerName = "Brain"
winnerScore = 45
def top_5_scores_file(winnerName, winnerScore):
run = True
try:
with open('Top_Score_File.txt', 'r') as f:
f.close()
except:
with open('Top_Score_File.txt', 'w+') as f:
f.close()
while run:
# This will open the top winners file if it exists
with open('Top_Score_File.txt', 'r+') as f:
topList = f.readlines()
topListLen = len(topList)
# This will go through the file and pick out
# The numbers from the file and make them into
# a useable list to find the lowest score
topListScores = []
for i in range(topListLen):
if (i % 2) == 1:
topListScores.append(topList[i])
i += 1
print(topListScores)
# This will now find the lowest score and
# remove it from the original file and replace
# it with the new score
topListScores.sort()
lowestScore = topListScores[0]
print(topList)
count = 0
topListLen = len(topList)
for item in range(topListLen):
if topList[count] == lowestScore:
del topList[count]
count -= 1
del topList[count]
else:
count += 1
print(topList)
winnerName = winnerName + '\n'
winnerScore = str(winnerScore) + '\n'
topList.append(winnerName)
topList.append(winnerScore)
f.truncate(0)
topListLen = len(topList)
for i in range(topListLen):
f.write(topList[i])
print(topList)
f.close()
run = False
top_5_scores_file(winnerName, winnerScore)