OUR OUR - 3 months ago 14
Python Question

Reading lines from a file after writing to it

I am trying to make a texting program.
The program asks you to insert your username and a password (and verify the password)
Now, after you're logged in, you can either write to someone else or read your file (after you create your account, the program will create a text file: .txt , and save the password at the first line)

If you want to log in after you exited the program, you can, because the program just needs to know if there's a .txt file with the username you inserted and to check the first line of that file to compare with the input (password).

The problem is when the page isn't clear (I wrote to that user)
I can't log in. I even print the first line and it matches perfectly with my input.
What is the problem?

My code: (only the part where I read the first line and compare with input)

with open(login_user+'.txt', 'r') as loginFile:
first_line = loginFile.readline()
loginFile.close()
while True:
login_password = raw_input('Password: ') # Taking password
if counter == 4:
print 'You failed 5 times, wait 30 seconds'
counter = 0
sleep(30)
elif login_password == first_line:
print '\nYou\'re connected to ' + login_user
break
else:
print(first_line)
print 'Incorrect password, Try again.'
counter += 1


Thank you very much in advance!

Answer Source

First, you don't need to type loginFile.close() as when using the with he's the one to handle it.

Second, fix the indentation between the with statement and the two rows afterwards.

Third, use rstrip in order to delete white-space at the end of the line as when you use raw_input it doesn't contain the white-space.

with open(login_user+'.txt', 'r') as loginFile:
    first_line = loginFile.readline().rstrip()

string.rstrip(s[, chars])

Return a copy of the string with trailing characters removed. If chars is omitted or None, white-space characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.