2017-04-04 214 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()