-1

I'm making a program where the user creates a username and then the program adds the username into a file, but for some reason I can't read the file.

usernames = open('usernames', 'r+')


def create_username():
        while True:
            username = str(input('create username: '))
            if len(username) > 12 or len(username) < 3:
                print('your username must be 3-12 characters long')
            elif username in usernames: 
                print('the username is already in use')
            elif len(username) <= 12:
                    usernames.write(username + '\n')
                    print('username created')
                    print('here\'s all the used usernames:',
usernames.read()) # i want this print function to print the whole file
                    usernames.close()
                    return username


create_username()

the content of the txt file looks like this:

afd

safds

asdfafsafsdafs

asfas

ok123

adsf

ffsda

afd

daf

fdsa

afsfas

dsaf

sadffas

dfasfdas

fdafsf

Ok so there is some other question that is similiar to this, but this one is unique because username in usernames makes the file pointer go to the last row of the file and in the other one it's because of read().

Juho Pesonen
  • 105
  • 1
  • 2
  • 9
  • Possible duplicate of [Why can't I call read() twice on an open file?](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file) – Aran-Fey Aug 13 '18 at 12:08
  • When you do `if username in usernames:`, you move the cursor to the end of the file. Then when you call `usernames.read()`, there's nothing left to read. By the way, if this didn't happen then your `usernames.write(username + '\n')` would overwrite the first line in the file. – Aran-Fey Aug 13 '18 at 12:09

1 Answers1

0

'username in usernames' is reading all the names from the file and positing the file pointer at the end of the file.

So, when you want to read all the usernames again, you must position the file pointer back to the start of the file.

lostbard
  • 5,065
  • 1
  • 15
  • 17