python 用户名和密码恢复系统的读取文件问题

reading file problem with python username and passowrd recovery system

这是一个恢复系统,用户可以在其中输入他们的唯一代码来恢复他们的详细信息。当输入唯一代码时,它会从文本文件中获取他们的详细信息,然后打印他们的用户名和密码。然后他们可以选择更改密码。我遇到的问题是,当我在其中输入旧密码时,它说密码不在该特定行中。文件中的格式是这样的:

(unique code) username: (username) password: (password)

global password1, password2,
check = True
while check:
    hash1=input("\n"+"Enter your unique code to recover your username or password ")
    with open("mount.txt","r") as file:
        for line in file:
            text = line.strip().split()
            if hash1 in text:
                print(line)
                check = False
                change = input("Do you want to change your password? [y,n]")
                while change not in('y', 'n'):
                    change = input("Do you want to change your password? [y,n]")
                if change == "y":
                    check = True
                    with open("mount.txt","r+") as file:
                        for line in file:
                            text = line.strip().split()
                            while check:
                                password1 = input("Enter old password ")
                                password2 = input("Enter new password ")
                                if len(password2) < 5:
                                    print("New password is too short")
                                elif password1 not in text:
                                    print("Old password is incorrect")
                                elif password1 in text:       
                                    s = open("mount.txt").read()
                                    s = s.replace(password1, password2)
                                    f = open("mount.txt", 'w')
                                    f.write(s)
                                    f.close()
                                    print("Password has been successfully changed")
                                    check = False

            elif len(hash1) < 32 and (check == True):
                print("Unique code not found please try again")
                break

因此,当我输入唯一代码时,它显示正确的行,然后当我尝试更改密码时,它一直说密码不在该特定行中。

目前,在文本文件中的行循环时,如果hash1不在任何行中,它会告诉你没有找到代码,并立即中断。

要解决此问题,您应该从 if hash1 in text 条件中中断或 return,然后测试 if len(hash1) < 32 and (check == True) 现在仅 运行 检查所有行后文件。

此外,假设文本是 'aslhngbadf username: bob password: alice',line.strip().split() 将是 ['aslhngbadf', 'username:', 'bob', 'password:', 'alice'],因此检查 password1 是否在 text 中对一个人不起作用密码的字母。但是,如果您输入单词 'password:' 或 'bob'... ,它会起作用,检查是否明确匹配 if password1 == text[4].

最后,当您重新打开并遍历文件时,您会从文本匹配的行移回文件顶部。不要打开 mount.txt 两次。 text 仍然可用,并且与您第一次设置时相比没有变化。