逐行读取TXT文件-Python

逐行读取TXT文件-Python,python,list,python-3.x,brute-force,Python,List,Python 3.x,Brute Force,如何让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 ite

如何让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) 如果输入任何其他密码,它将超过列表中的所有密码并返回“无”

所以我想我应该告诉python一次测试一行


“return input()”是一种输入,因此对话框不会自动关闭,没有任何内容可输入。

首先,尝试搜索重复的帖子

例如,我在处理txt文件时通常使用的内容:

lines = [line.rstrip('\n') for line in open('filename')]

首先,尝试搜索重复的帖子

例如,我在处理txt文件时通常使用的内容:

lines = [line.rstrip('\n') for line in open('filename')]

readlines
返回包含文件中所有剩余行的字符串列表。正如python文档所述,您还可以使用
list(infle)
读取所有ines()

但您的问题是python读取包含换行符的行(
\n
)。文件中只有最后一行没有换行符。因此,通过比较
guess==real
您可以比较
'password1\n'=='password1'
,这是
False

要删除换行符,请使用
rstrip

chars = [line.rstrip('\n') for line in inFile]
此行而不是:

chars = inFile.readlines()

readlines
返回包含文件中所有剩余行的字符串列表。正如python文档所述,您还可以使用
list(infle)
读取所有ines()

但您的问题是python读取包含换行符的行(
\n
)。文件中只有最后一行没有换行符。因此,通过比较
guess==real
您可以比较
'password1\n'=='password1'
,这是
False

要删除换行符,请使用
rstrip

chars = [line.rstrip('\n') for line in inFile]
此行而不是:

chars = inFile.readlines()

我有点担心你似乎以明文形式存储密码。@TomdeGeus你的陈述绝对有效,但如果我猜,这可能是一个练习,而不是一个真正的应用程序。我有点担心你似乎以明文形式存储密码。@TomdeGeus你的陈述绝对有效,但如果我猜,这可能是一个练习,而不是一个真正的应用程序。