好吧所以我希望当用户想要检查高分时输出会按降序打印数据时请记住.txt文件中有名称和数字这就是我发现这个的原因所以硬。如果您还有其他需要,请在
中告诉我def highscore():
global line #sets global variable
for line in open('score.txt'):
print(line)
#=================================================================================
def new_highscores():
global name, f #sets global variables
if score >= 1:#if score is equal or more than 1 run code below
name = input('what is your name? ')
f = open ('score.txt', 'a') #opens score.txt file and put it into append mode
f.write (str(name)) #write name on .txt file
f.write (' - ') #write - on .txt file
f.write (str(score)) #write score on .txt file
f.write ('\n') #signifies end of line
f.close() #closes .txtfile
if score <= 0: #if score is equal to zero go back to menu 2
menu2()
我添加了这个,以防万一我在文件上写的方式有问题
答案 0 :(得分:0)
最简单的方法是将高分文件保持在排序状态。这样每次你想打印出来的时候,就去做吧。添加分数时,请再次对列表进行排序。这是new_highscores
的一个版本,它完成了:
def new_highscores():
""""Adds a global variable score to scores.txt after asking for name"""
# not sure you need name and f as global variables without seeing
# the rest of your code. This shouldn't hurt though
global name, f # sets global variables
if score >= 1: # if score is equal or more than 1 run code below
name = input('What is your name? ')
# here is where you do the part I was talking about:
# get the lines from the file
with open('score.txt') as f:
lines = f.readlines()
scores = []
for line in lines:
name_, score_ = line.split(' - ')
# turn score_ from a string to a number
score_ = float(score_)
# store score_ first so that we are sorting by score_ later
scores.append((score_, name_))
# add the data from the user
scores.append((score, name))
# sort the scores
scores.sort(reverse=True)
# erase the file
with open('score.txt', 'w') as f:
# write the new data
for score_, name_ in scores:
f.write('{} - {}\n'.format(name_, score_))
if score <= 0: # if score is equal to zero go back to menu 2
menu2()
你会注意到我正在使用with
声明。您可以了解有关here的更多信息,但基本上它的工作原理如下:
with open(filename) as file:
# do stuff with file
# file is **automatically** closed once you get down here.
即使你出于另一个原因离开了这个块(抛出了异常,你提前从函数返回等等)使用with
语句是一种更安全的处理文件的方法,因为你基本上是让Python为你处理文件的关闭。 Python永远不会像程序员那样忘记。
P.S。,有一种名为binary search的方法会更有效率,但我觉得你刚刚开始,所以我想保持简单。基本上你要做的是通过在每个点将搜索区域减半来搜索文件中应插入新分数的位置。然后当你回写文件时,只写出不同的东西(从新分数开始。)