User login read from file failing compared to user input
<p>I'm writing a program that will verify a username:</p>

<pre><code>def user_login():
    """ Login and create a username, maybe """
    with open('username.txt', 'r') as f:
        if f.readline() is "":
            username = raw_input("First login, enter a username to use: ")
            with open('username.txt', 'a+') as user:
                user.write(username)
        else:
            login_id = raw_input("Enter username: ")
            if login_id == str(f.readline()):
                return True
            else:
                print "Invalid username."
                return False


if __name__ == '__main__':
    if user_login() is not True:
        print "Failed to verify"
</code></pre>

<p>Everytime I run this it outputs the following:</p>

<pre><code>Enter username: tperkins91
Invalid username.
Failed to verify
</code></pre>

<p>How do I compare user input to reading from a file?</p>

<p>When you use <code>readline()</code> the first time the current file position is moved past the first record.   A better way to find if the file is empty is to test it's size:</p>

<pre><code>import os.path
import sys

def user_login():
    fname = 'username.txt'

    """ Login and create a username, maybe """
    if os.path.getsize(fname) == 0:

        with open(fname, 'w') as f:
            username = raw_input("First login, enter a username to use: ")
            f.write(username)
            return True    #/False --&gt; make the function return a bool in this branch
    else:
        with open(fname, 'r') as f:
            login_id = raw_input("Enter username: ")
            if login_id == f.readline().rstrip():
                return True
            else:
                print &gt;&gt;sys.stderr, "Invalid username."
                return False


if __name__ == '__main__':
    if user_login() is not True:
        print "Failed to verify"
</code></pre>

<p><code>f.readline()</code> will include a trailing newline, if there is one in the file, whereas <code>raw_input()</code> will not.  While we don't explicitly write one, someone might edit the file and add a newline unintentionally, hence the addition of the <code>rstrip()</code> as a defensive precaution.</p>

python python-2.7 file user-input