Python 与用户输入相比,从文件读取的用户登录失败

Python 与用户输入相比,从文件读取的用户登录失败,python,python-2.7,file,user-input,Python,Python 2.7,File,User Input,我正在编写一个验证用户名的程序: def user_login(): """ Login and create a username, maybe """ with open('username.txt', 'r') as f: if f.readline() is "": username = raw_input("First login, enter a username to use: ") with open

我正在编写一个验证用户名的程序:

def user_login():
    """ Login and create a username, maybe """
    with open('username.txt', 'r') as f:
        if f.readline() is "":
            username = raw_input("First login, enter a username to use: ")
            with open('username.txt', 'a+') as user:
                user.write(username)
        else:
            login_id = raw_input("Enter username: ")
            if login_id == str(f.readline()):
                return True
            else:
                print "Invalid username."
                return False


if __name__ == '__main__':
    if user_login() is not True:
        print "Failed to verify"
每次我运行它时,它都会输出以下内容:

Enter username: tperkins91
Invalid username.
Failed to verify

如何将用户输入与读取文件进行比较?

在另一个嵌套上下文中再次打开同一文件不是一个好主意。相反,在追加模式下打开文件一次,并在需要时使用
f.seek(0)
返回到开始:

def user_login():
    """ Login and create a username, maybe """
    with open('username.txt', 'a+') as f:
        if f.readline() is "":
            username = raw_input("First login, enter a username to use: ")
            f.seek(0)
            f.write(username)
            # return True/False --> make the function return a bool in this branch
        else:
            login_id = raw_input("Enter username: ")
            f.seek(0)
            if login_id == f.readline():
                return True
            else:
                print "Invalid username."
                return False


if __name__ == '__main__':
    if user_login() is not True:
        print "Failed to verify" 

在<代码中返回一个布尔值>如果分支是您可能需要考虑的问题,那么函数的返回类型与BoL一致,而不是<>代码> No.。p> 当当前文件位置第一次移过第一条记录时使用

readline()
时。确定文件是否为空的更好方法是测试其大小:

import os.path
import sys

def user_login():
    fname = 'username.txt'

    """ Login and create a username, maybe """
    if os.path.getsize(fname) == 0:

        with open(fname, 'w') as f:
            username = raw_input("First login, enter a username to use: ")
            f.write(username)
            return True    #/False --> make the function return a bool in this branch
    else:
        with open(fname, 'r') as f:
            login_id = raw_input("Enter username: ")
            if login_id == f.readline().rstrip():
                return True
            else:
                print >>sys.stderr, "Invalid username."
                return False


if __name__ == '__main__':
    if user_login() is not True:
        print "Failed to verify"
f.readline()
将包含尾随的换行符(如果文件中有),而
raw\u input()
将不包含尾随的换行符。虽然我们没有显式地编写一个,但可能有人无意中编辑了文件并添加了一个换行符,因此添加了
rstrip()
,作为防御措施