从外部txt.file读取/写入时,IF语句将被忽略

在这里是初学者程序员,我正在尝试制作一个程序,该程序可以用作注册和检查所估算的用户名是否已被使用的方式。我的代码不会产生任何错误,但是如果使用了用户名,则IF语句始终会被忽略,并且不会产生错误消息。

username = input("Username: ")
def register():
    with open("Usernames.txt", "r+") as f:
        f.write("\n")
        for line in f:
            if line == username :
                print("Error")
            else:
                f.write(username)

register()
评论
  • 女人!依旧
    女人!依旧 回复

    input strips the newline from input it reads; a file iterator does not.

    username = input("Username: ")
    def register():
        with open("Usernames.txt", "r+") as f:
            f.write("\n")
            for line in f:
                line = line.rstrip('\n')
                if line == username :
                    print("Error")
                else:
                    f.write(username)
  • 我喜欢她
    我喜欢她 回复

    You need to use f.readlines() in your code

    for line in f.readlines():
        if line == username :
            print("Error")
        else:
            f.write(username)