Why can’t I write to a file despite using “append” mode?

I’m trying to create a basic login system with Python that only includes a username. Here is a snippet of what I’m having issues with.

I added a few usernames to the .txt file and it can find conflicts or login properly but it can’t actually register a username. I’ve done some research and am opening the file in “append” mode and using the write command.

def register():
   file1 = open("C:/test/User_Dat.txt", "a")
   global username
   username = str(input("Please enter a username n")).lower()
   readfile = file1.read()
   if username in readfile: 
        print('The user', username, 'has already been created.')
        welcome()
   else: 
        print('The user', username, 'has been created!')
        file1.write(username)
        file1.write("n")
        file1.close()
        login()

But I still get an error like this:

io.UnsupportedOperation: not writable

Why is the file not writable?

Answer

EDITED:

You are opening file in reading mode. Fix this line as follows:

file1 = open("C:/test/User_Dat.txt", "r+")

Documentation: https://docs.python.org/3/library/functions.html#open