Home > Net >  append text from input without changing previous text in python
append text from input without changing previous text in python

Time:12-31

i want to make python create a file if it doesn't exist ,then take text from users input and append into my file and to be able to use my code several times without changing text before it

def register():
    f=open('1.txt','w')    
    f=open('1.txt','r')
    users=f.readlines()
    f=open('1.txt','a')
    while True:
        username = input('Enter your username: ')
        password = input('Enter your password: ')
        if username in users:
            print('this username is taken')
        else:
            f.write(f'{username}\n')
            f.write(f'{password}')
            break

this is my code

CodePudding user response:

EAFP approach (which is more pythonic that LBYL):

  • try to create a file
  • handle specific exception if it exists
  • either way do your logic in finally block
try:
    with open("1.txt","x") as f: pass
except FileExistsError:
    print("File already exists!")
finally:
    with open("1.txt", "r ") as f:
        lines = f.readlines()
        username, password = input("Type username and password (separated by a space): ").split()
        if f"{username}\n" in lines:
            print('This username is taken!')
        else:
            f.writelines([f"{username}\n",f"{password}\n"])

Keep in mind though that:

  • if the username and password are the same this won't work correctly (or at least not as expected imho, as homework figure out why :D )
  • passwords in general should NOT be kept as plain text
  • you should add the "boilerplate" if __name__=="__main__": thingy if it's a standalone and no part of a function/class etc
  • you could wrap the input in try...except ValueError block to be extra safe when somebody enters a single value or three values and so on

Comments: If you do something like this:

    f=open('1.txt','w')    
    f=open('1.txt','r')

The 2nd line shadows the first one, so it makes no sense, it's the same as:

x=2
x=3
print(x)

The 1st assignment is "dead"

  • Most often you want to use with when handling files operations, otherwise it's your responsibility to close the file as well.

To people who are going to downvote: Feel free to do so, but don't be a lazy lad and be so nice to comment WHY, otherwise it makes no sense to vote and this service becomes garbage...

  • Related