2017-04-04 217 views
0

如何告诉python逐行读取txt列表? 我正在使用.readlines(),似乎没有工作。逐行读取TXT文件 - Python

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测试每一行一次吗?

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

+0

http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-in-python –

+1

我有点担心你看起来存储密码纯文本。 –

+0

@TomdeGeus你的陈述绝对有效,但如果我猜测,这可能是一个练习,而不是一个真正的应用程序。 – Aaron

回答

2

readlines返回与文件中的所有剩余行字符串列表。由于python文档说明您也可以使用list(inFile)读取所有INES(https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects

但你的问题是,蟒蛇读取包括换行符(\n)线。只有最后一行在文件中没有换行符。因此,通过比较guess == real你比较'password1\n' == 'password1'这是False

要删除换行符使用rstrip

chars = [line.rstrip('\n') for line in inFile] 

这一行,而不是:

chars = inFile.readlines()