Peyton Anderson
Peyton Anderson

Reputation: 11

Is there a way to not delete the user input in a text file after running it again?

Whenever I run this program it will ask for a username and a password, store them as the first values in the two lists, open up a text file, and then write password: and username: then whatever username_Database[0] and password_Database[0] are. The problem is when I run the program again, it deletes the previous values. Is there anyway to save the user input and not have it deleted when I run the program again?

import time

username_Database = []
password_Database = []

username = input("Enter a username\n")
username_Database.append(username)

password = input("Enter a password\n")
password_Database.append(password)

print('You are now registered and your user name is \n' + username_Database[0] + "\n and your password is \n" + password_Database[0] + "\n")
print("Saving...")

filename = open("data.txt", "w")
filename.add("Password: " + str(password_Database[0] + "\n"))
filename.add("Username: " + str(username_Database[0] + "\n"))


time.sleep(2)
exit()

Upvotes: 1

Views: 130

Answers (1)

taipei
taipei

Reputation: 1055

You are using write mode when opening the file, it will overwrite everything inside the file. Change it to append mode.

# Using append mode
filename = open("data.txt", "a")

# It should be write instead of add
filename.write ("Password: " + str(password_Database[0] + "\n"))
filename.write ("Username: " + str(username_Database[0] + "\n"))

Upvotes: 3

Related Questions