对照某一行检查变量。python

对照某一行检查变量。python,python,python-3.x,Python,Python 3.x,我正在用Python 3做一个游戏。我需要检查一下玩家输入的用户名和密码是否正确。用户名和密码在一个文件中,用户注册后会将它们放在那里 def login_signup(): loginsignup = input("Do you want to login or sign up? Enter L/S: ") if loginsignup == "S": userpassA = open("USERPASS.txt.txt", "a")

我正在用Python 3做一个游戏。我需要检查一下玩家输入的用户名和密码是否正确。用户名和密码在一个文件中,用户注册后会将它们放在那里

def login_signup():

    loginsignup = input("Do you want to login or sign up? Enter L/S: ")

    if loginsignup == "S":  

        userpassA = open("USERPASS.txt.txt", "a")

        user = input("Please enter a username: ")
        password = input("Please enter a password: ")

        userpassA.write(user)
        userpassA.write("\n")
        userpassA.write(password)
        userpassA.close()

    if loginsignup == "L":  # Here is where it needs to be.

        userpassR = open("USERPASS.txt.txt", "r")
        lines = userpassR.readline()

        username = input("Username: ")
        # passwordl = input("Password: ")

        if username == lines[0]:
            print("Right.")

        userpassR.close()
每次调用userpassR.readline(),都会读取文件中的下一行,而不是一次读取所有行。假设文件“USERPASS.txt.txt”中的内容是

user1
mypswd
,第一次调用userpassR.readline()时,将返回一个字符串
'user1\n'
。下次调用它时,返回值将是
'mypswd'

因此,要修改代码,请执行以下操作:

if loginsignup == "L":  # Here is where it is.

userpassR = open("USERPASS.txt.txt", "r")
line1 = userpassR.readline()      # It's only one line
line2 = userpassR.readline()      # It's another line

username = input("Username: ")
password = input("Password: ")

if username == line1[:-1]:         # I removed the '\n' at the end of line1
    print("Username Right.")

if password == line2:              # There isn't a '\n' here
    print("Password Right.")

userpassR.close()

这里的问题是什么?您是否收到错误?我不确定这是最好的方法,除非您将文件名设置为唯一。而且文件名真的是
USERPASS.txt.txt
我猜你还有一个额外的
.txt
。您可以在文件上循环,如果第一个值与用户输入的值不匹配,则终止程序。我不确定,但它只是结束程序,从来没有说用户名和密码是否正确。没有错误。我不敢相信还没有人提到过这一点——在文件中写入明文密码是一个巨大的安全漏洞。如果有人破坏了你的计算机/服务器,他们将拥有每个人的密码和用户名,这些密码和用户名可能用于其他网站/游戏。相反,用加密安全的散列对密码进行散列,对其加盐并存储。然后比较哈希而不是密码。你意识到你没有在密码后写换行,对吗?因此,您的文件将看起来像
user1
然后是
pass1user2
然后是
pass2user3
等等。这将使检查任何东西变得非常困难。