如何告诉 python 逐行读取 txt 列表?我正在使用 .readlines() ,它似乎不起作用。
import itertools
import string
def guess_password(real):
inFile = open('test.txt', 'r')
chars = inFile.readlines()
attempts = 0
for password_length in range(1, 9):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == real:
return input('password is {}. found in {} guesses.'.format(guess, attempts))
print(guess, attempts)
print(guess_password(input("Enter password")))
test.txt 文件如下所示:
1:password1
2:password2
3:password3
4:password4
当前,该程序仅使用列表中的最后一个密码 (password4) 运行,如果输入了任何其他密码,它将跳过列表中的所有密码并返回“none”。
所以我假设我应该告诉 python 一次测试每一行?
附注。“return input()”是一个输入,这样对话框不会自动关闭,没有什么可输入的。
readlines
返回包含文件中所有剩余行的字符串列表。正如 python 文档所述,您还可以使用list(inFile)
读取所有 ines ( https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects )
但您的问题是 python 读取包含换行符 ( \n
)的行。并且只有最后一行在您的文件中没有换行符。所以通过比较guess == real
你比较'password1\n' == 'password1'
哪个是False
要删除换行符,请使用rstrip
:
chars = [line.rstrip('\n') for line in inFile]
这一行而不是:
chars = inFile.readlines()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句