在文本文件中查找单词

问题描述 投票:0回答:3

我试着为自己创建一个小密码破解程序。问题是该程序总是告诉我:Password not found!我使用一行只有一个单词的文本文件!

pw = "password"

# The password in the list is "password"

pwlist = open('passwordlist.txt', 'r')
words = pwlist.readlines()
found = False

for password in words:
    if str(password) == pw:
        print(password)
        found = True
        break


if found == True:
   print("password found!")
else:
   print("Password not found!")
python file passwords text-files word
3个回答
0
投票

方法readlines()不会从行中删除尾随回车。尝试

if password.strip() == pw: 

0
投票

这段代码看起来应该工作正常...你能确认.txt文件中的单词确实是“密码”(拼写方式相同,没有多余的字符/空格等)?


0
投票

readline()方法在每行\n(新行转义序列)的末尾拾取换行符。

你会注意到,如果你打开你的文本文件,它实际上是两行,第二行只有长度0

所以要做到这一点,你需要更换:

words = pwlist.readlines()

有了这个:

words = [line.rstrip('\n') for line in pwlist]
© www.soinside.com 2019 - 2024. All rights reserved.