python - 编写程序以将高分存储在 .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!")
解决方案
所以你的代码应该是这样的:
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!")
推荐阅读
- pytest - Pytest 会话夹具不再执行
- json - 如何使用 scala spark 将 JSON 数组拆分为多个 JSON
- tunnel - 无法在 Wireshark 中剖析 L2TPV3
- postgresql - JPA 一对一加入 @Id 列。参考表中未更新的连接列
- objective-c - AVFoundation - 曝光没有改变
- mysql - 如何将“Mysql JOIN”与同一张表的 sql 文本一起使用
- azure - Terraform:如何从数据模块中获取块内的属性
- java - 使用 JEP 时出现 UnsatisfiedLinkError
- java - 尝试借助 servlet 将视频(mp4)从 Web 服务器(nginx)流式传输到使用视频标签(HTML)的客户端
- c# - 通过 unc 获取/设置 azure 文件的元数据