Python3密码检查器将只读取确切的txt文件内容

2024-09-30 01:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的密码检查器正在工作,但是只有当用户输入与整个.txt文件相同时,它才会解析。你知道吗

如何在.txt文件中输入多个密码,并在其中任何一个密码与输入匹配时使程序正常工作?我想能够添加密码123456,这样我的第二个if语句将工作。你知道吗

#simple program to check passwords against a txt file database

passwordfile = open('secretpasswordfile.txt')
secretpassword = passwordfile.read()
print('Enter your password.')
typedpassword = input()
if typedpassword == secretpassword:
    print('Access granted.')
    if typedpassword == '123456':
        print('This password is not secure.')

else:
    print('Access denied.')

那个secretpasswordfile.txt文件只写了genericpassword。你知道吗


Tags: 文件用户程序txt密码ifaccesspassword
1条回答
网友
1楼 · 发布于 2024-09-30 01:32:26

假设文件中的每个密码都由一个新行分隔,您可以检查其中是否有与此代码匹配的密码。它使用这样一个事实:您可以将open返回的file对象视为文件中每一行的迭代器,并将键入的密码与每一行进行比较。.strip()是从每一行中拉出尾随的换行符。你知道吗

passwordfile = open('secretpasswordfile.txt')
print('Enter your password.')
typedpassword = input()
if any(typedpassword == pw.strip() for pw in passwordfile):
    print('Access granted.')
    if typedpassword == '123456':
        print('This password is not secure.')
else:
    print('Access denied.')

相关问题 更多 >

    热门问题