Sunday 12 November 2017

list - Read TXT file line by line - Python





How can I tell python to read a txt list line by
line?

I'm using .readlines() which doesn't seem to be working.



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")))


The
test.txt file looks
like:




1:password1
2:password2
3:password3
4:password4


currently
the program only works with the last password on the list (password4)
if any
other password is entered it will run past all the passwords on the list and return
"none".




So I assume I should be
telling python to test each line one at a
time?



PS. the "return input()" is an input so
that the dialog box doesn't close automatically, there's nothing to be
inputted.



Answer




readlines returns a
list of strings with all remaining lines in the file. As the python docs state you could
also use list(inFile) to read all ines ( href="https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects"
rel="nofollow
noreferrer">https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects)



But
your problem is that python reads the line including the newline character
(\n). And only the last line has no newline in your file. So by
comparing guess == real you compare 'password1\n'
== 'password1'
which is
False



To remove the
newlines use
rstrip:




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


this line
instead of:



chars =
inFile.readlines()


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...