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>Opening the same file again in another nested context is not a good idea. Instead, open the file once in <em>append</em> mode, and use <code>f.seek(0)</code> to return to the start whenever you need to:</p>

<pre><code>def user_login():
    """ Login and create a username, maybe """
    with open('username.txt', 'a+') as f:
        if f.readline() is "":
            username = raw_input("First login, enter a username to use: ")
            f.seek(0)
            f.write(username)
            # return True/False --&gt; make the function return a bool in this branch
        else:
            login_id = raw_input("Enter username: ")
            f.seek(0)
            if login_id == 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>Returning a bool value in the <code>if</code> branch is something you may want to consider so the return type of your function is consistent as bool, and not <code>None</code> as in the current case.    </p>

python python-2.7 file user-input