在python 2.7中只读行而不是整个行

时间:2018-02-10 16:33:39

标签: python python-2.7

如果在注册用户名和密码时如下所示,它会在txt文件中添加一个新行,当你登录时,它会检查txt文件中的每一行 并且如果任何行与登录匹配,则将其声明为正确,而不是检查用户名和密码是否与整个事物匹配

print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for 
register: ")
if option == "R":
    print "Warning Only 1 user can be registered"
    usernamer = raw_input("Desired Username: ")
    passwordr = raw_input("Desired Password: ")
    file = open("Username.txt","w")
    file.write(usernamer + '\n')
    file.close()
    file = open("Password.txt","w")
    file.write(passwordr + '\n')
    file.close
    print "Registered"
else:
    usr = raw_input("Username: ")
    pss = raw_input("Password: ")
    file = open("Username.txt","r")
    if usr == file.read():
        print "Username correct"
        file.close()
    else:
            print "Username incorrect or not registered"
            file.close()
    file = open("Password.txt","r")
    if pss == file.read():
        print "Password correct"
        file.close()
    else:
            print "Password incorrect or not registered"
            file.close()

3 个答案:

答案 0 :(得分:1)

以下是如何查找文件的某一行是否存在字符串:

contain = False # Indicator of whether some line of a file contains the string
with open(FILENAME, 'r') as file: # Use `with` statement to automatically close file object
    for line in file:
        if string in line:
            contain = True
            break

答案 1 :(得分:0)

如果您只是想检查用户是否在文件内容中,

  

if usr in file.read():
    do_somethin

“==”检查值是否与原样相同,“in”关键字检查子串是否在巨大的字符串中。在file.read()中,将整个内容作为字符串。

答案 2 :(得分:0)

我已修改您的代码以使用密码检查逻辑验证密码和用户名。这应该有用。

print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for register: ")
if option == "R":
    print "Warning Only 1 user can be registered"
    usernamer = raw_input("Desired Username: ")
    passwordr = raw_input("Desired Password: ")
    file = open("Username.txt","a")
    file.write(usernamer + '\n')
    file.close()
    file = open("Password.txt","a")
    file.write(passwordr + '\n')
    file.close
    print "Registered"
else:
    usr = raw_input("Username: ")
    pss = raw_input("Password: ")
    file = open("Username.txt","r")
    count = 0
    userfound = False
    try:
        for user in file.readlines():
            count += 1
            if usr == user.strip():
                userfound = True
        file.close()
        if not userfound:
            raise
        file = open("Password.txt","r")
        passcount = 0
        for passcode in file.readlines():
            passcount += 1
            if count == passcount:
                if pss == passcode.strip():
                    print 'successfully logged in'
                else:
                    print "Password incorrect or not registered"
                break

        file.close()
    except Exception as e:
        print 'User login error !!!'