我正在创建一个高分数据库,到目前为止有两件事情无效.
如果我输入一个已存在于文件中的名称,它将忽略if语句(在代码中提到)我会对它在哪一行发表评论.
当我输入名称和分数时,它将替换highscores.txt文件中的当前名称和分数.
这是我的档案:
name = str(input("Enter your name: "))
score = str(input("Enter your score: "))
file = open("N:\highscores.txt", "r")
if(name in file):
print("You have already entered a score.")
file.close()
else:
file = open("N:\highscores.txt", "w")
file.writelines(name + " : " + score + "\n")
file.close()
Run Code Online (Sandbox Code Playgroud)
此外,当我解决这个问题时,我如何按大小顺序订购它们?例如:1.450 2. 300等
谢谢.
Python文件对象不支持in成员资格测试,不.
将文件读入字典,然后对其进行测试:
with open("N:\highscores.txt", "r") as scoresfile:
scores = {name.strip(): score.strip() for line in scoresfile if ':' in line for name, score in (line.split(':'),)}
if name in scores:
print("You have already entered a score.")
else:
with open("N:\highscores.txt", "a") as scoresfile:
file.write('{} : {}\n'.format(name, score))
Run Code Online (Sandbox Code Playgroud)
请注意,您需要以附加模式打开文件以添加行; w将首先清除打开的文件.