逐行读取 TXT 文件 - Python

Read TXT file line by line - Python

如何让 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) 如果输入任何其他密码,它将 运行 超过列表中的所有密码和 return "none".

所以我假设我应该告诉 python 一次测试每一行?

PS。 "return input()"是一个输入,所以对话框不会自动关闭,没有什么可输入的。

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

How do I read a file line-by-line into a list?

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

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

readlines returns 包含文件中所有剩余行的字符串列表。正如 python 文档所述,您还可以使用 list(inFile) 读取所有指令 (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()