使用python用户名和passowrd恢复系统读取文件问题

时间:2019-01-24 19:40:37

标签: python python-3.x recovery

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

(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

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

1 个答案:

答案 0 :(得分:0)

当前,当循环遍历文本文件中的行时,如果hash1不在ANY行中,它将告诉您未找到代码,并立即中断。

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

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

最后,当您重新打开文件并对其进行操作时,您将从文本匹配的行移回到文件顶部。不要两次打开mount.txt。 text仍然是可用的,自首次设置以来就没有变化。