首页 > 解决方案 > 编写程序以将高分存储在 .txt 文件中

问题描述

我正在为一个学校项目编写一个程序,我必须在其中存储来自用户输入的高分。我已经完成了大部分程序,除了从/向我完全一无所知的文件读取/写入。

说明说您应该能够拥有五个以上的用户,但只有五个最好的用户会被保存到文件中。分数应该从高到低排序,并且用户应该能够更新他们之前的分数。

这是我到目前为止所拥有的:

class highscoreUser:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    @classmethod
    def from_input (cls):
        return cls(
            input("Type the name of the user:"),
            float(input("Type the users score")),
            )


print("Welcome to the program! Choose if you want to continue using this program or if you want to quit! \n -Press anything to continue. \n -or type quit to exit the program.")
choice = input("What would you like to do?:")
choice = choice.lower()

while choice != "quit":

    try:
        NUMBER = int(input ("How many people are adding their highscores?"))

    except:
        print("Something went wrong, try again!")
        choice !="quit"

    users = {}

    try:
        for i in range(NUMBER):
            user = highscoreUser.from_input()
            users[user.score] = user

    except:
        print("")
        choice !="quit"


这是我需要帮助的地方:

 while choice != "quit":
        print("\n.Now you have multiple choices: \n1.Uppdatera highscore. \n2.Hämta highscore \n3.Quit to exit the program  ")
        choice = input("What would you like to do?:")
        choice = choice.lower()

      # if choice == "1":
      #     with open("highscore.txt", "w") as scoreFile:
      #     ###Function to write/update the file with the user dictionary

      # elif choice == "2":
      #     with open("highscore.txt", "r") as scoreFile
      #     ###Function for reading the highscore file

      # elif choice == "quit":
      #     print("\nThank you for using this program!")

      # else:
      #     print("\nSomething went wrong, try again!")

标签: pythonfile

解决方案


所以你的代码应该是这样的:

while choice != "quit":
    print("\n.Now you have multiple choices: \n1.Uppdatera highscore. \n2.Hämta highscore \n3.Quit to exit the program  ")
    choice = input("What would you like to do?:")
    choice = choice.lower()

    if choice == "1":
        with open('highscore.txt', 'wb') as f:
        pickle.dump(users, f)

    elif choice == "2":
        with open('highscore.txt', 'rb') as f:
            users = pickle.load(f)
    
    elif choice == "quit":
        print("\nThank you for using this program!")

    else:
        print("\nSomething went wrong, try again!")

推荐阅读