if(x in y)不能在python文件I / O中工作

时间:2013-12-02 13:58:51

标签: python file io

我正在创建一个高分数据库,到目前为止,有两件事情无效。

  1. 如果我输入一个已存在于文件中的名称,它会忽略if语句(在代码中提到)我会对它在哪一行发表评论。

  2. 当我输入名称和分数时,它会替换highscores.txt文件中的当前名称和分数。

  3. 这是我的档案:

    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()
    

    此外,当我解决此问题时,如何按大小顺序订购?例如: 1. 450 2. 300等。

    感谢。

2 个答案:

答案 0 :(得分:7)

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))

请注意,您需要在追加模式下打开文件以添加行; w将首先清除打开的文件。

答案 1 :(得分:2)

通过打开,您只是准备好使用该文件。您必须为要读取的文件内容执行file.read()