2017-04-04 13 views
0

pythonに行ごとにtxtリストを読み込ませるにはどうすればよいですか? 私は動作していないようです.readlines()を使用しています。TXTファイルを1行ずつ読む - 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) 他のパスワードが入力されている場合、それは過去のすべての実行されますパスワードをリストに追加し、 "none"を返します。

だから、私は一度に1行ずつテストするようにpythonに指示しなければならないと思いますか?

PS。 "return input()"はダイアログボックスが自動的に閉じないように入力され、何も入力されません。

+0

http://stackoverflow.com/questions/8009882のでguess == realを比較することによって、あなたはrstripを使用する改行を削除するにはFalse

ある'password1\n' == 'password1'を比較します/大文字の読み方大ファイルの行単位で –

+1

パスワードをプレーンテキストで保存するように思われるのではないかと心配しています。 –

+0

@TomdeGeusあなたの声明は間違いなく有効ですが、もし私が推測しなければならないのは、実際の応用ではなく、おそらく運動です。 – Aaron

答えて

2

readlinesすると、ファイル内の残りのすべての行で文字列のリストを返します。 Pythonのドキュメントは、状態として、あなたはまた、すべてのINES(https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects

を読むためにlist(inFile)を使用することができますしかし、あなたの問題は、Pythonは改行文字(\n)を含む行を読み込むことです。そして最後の行だけがあなたのファイルに改行文字がありません。

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

このラインの代わりに::

chars = inFile.readlines() 
1

まず、重複した投稿を検索してみてください。例えば

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

、何のtxtファイルを扱うとき、私は通常使用しています:

lines = [line.rstrip('\n') for line in open('filename')] 
関連する問題