user12183354
user12183354

Reputation:

How do i save data into a .txt file instead of making a new file (Python)

I am making a quiz and i ahve made this simple login system. It works perfectly fine but i have a small issue. The issue is that whenever someone makes a new account, it creates a new .txt file and doesn't write it in the usernames.txt file. Can anyone help me resolve this? (This is the code down below)

welcome = input("Do you have an acount? y/n: ") # asks the user if they have a account
if welcome == "n":
    while True:
        username  = input("Enter a username: ")
        password  = input("Enter a password: ")
        password1 = input("Confirm password: ")
        if password == password1:
            file = open(username+".txt", "w")
            file.write(username+":"+password)
            file.close()
            #saved the username and password so that they can Login in.
            welcome = "y"
            break
        print("Passwords do NOT match!")

if welcome == "y":
    while True:
        login1 = input("Login: ")
        login2 = input("Password: ")
        file = open(login1+".txt", "r")
        data   = file.readline() #reads the file if the account exists
        file.close()
        if data == login1+":"+login2:
            print("Welcome") #if matches then they can start the quiz
            break
        print("Incorrect username or password.")```

Upvotes: 0

Views: 436

Answers (2)

Velcorn
Velcorn

Reputation: 60

It seems that you want this instead, because your code creates a new file for each new username:

if password == password1:
    with open("usernames.txt", "a") as f:
        f.write(username+":"+password+"\n")

...

while True:
        login1 = input("Login: ")
        login2 = input("Password: ")
        with open("usernames.txt", "r") as f:
            if login1+":"+login2 in f.read():
                print("Welcome") #if matches then they can start the quiz
            else:
                print("Incorrect username or password.")

Using with open as a shortcut for your file opening and closing. Also changed your check if the account exists in your text file as it will probably be holding more than one user:pass.

Upvotes: 1

meyer1994
meyer1994

Reputation: 387

As the documentation states, you need to use the flag a, for append mode, in the open function. See below:

$ echo "user_1" > usernames.txt
$ cat usernames.txt 
user_1
$ python
>>> with open('usernames.txt', 'a') as file:
...     file.write('user_2\n')
... 
7
>>> 
$ cat usernames.txt 
user_1
user_2

This way, you just need to change the open function inside your first if statement to open('filename.txt', 'a'). Remember to add a newline when writing to the file. Or the names will be placed in the same line.

However, you may want to check your code. As @MotKohn pointed out, you are creating a new file named after the user. Maybe that is not the behaviour you are expecting.

Upvotes: 1

Related Questions