I just started my gcse computer science course where we learn python. I need help with updating a user’s score to a certain account. I am storing usernames passwords and scores in a text file and need to know how to change a score from a certain account. My text file is set out like this:
Bobby,pass,98
Pip,Noob,19
pog,man,1234
E.g Bobby is the username and pass is the password and 98 is the score so what I need is a way to scan for that certain username and change the score (98).
The code that I use for creating an account and logging in is this:
def SignUp():
print("""Please enter a username and password.""")
newUsername = input("Your username: ")
#Now askes for a password
print("""Cool now enter a password
""")
newPassword = input("Your Password: ")
print("Nice.")
newscore = input("Now give me a score")
#Puts the username and password into a txt
file = open("Login.txt","a")
file.write("""
""")
file.write (newUsername)
file.write (",")
file.write (newPassword)
file.write (",")
file.write (newscore)
file.close()
def Login():
userLogin = input("Please enter your username. ")
userPass = input("Password: ")
logged_in = False
with open('Login.txt', 'r') as file:
for line in file:
username, password, score = line.split(',')
if username == userLogin:
# Check the username against the one supplied
logged_in = password == userPass
print(str(score))
print("you logged in")
break
SignUp()
Login()
I’m quite new to python as you can probably tell so any help will be appreciated.
>Solution :
The easiest way is to read the entire file, then rewrite the entire thing with the changed number. This is only practical with small files:
def changeScore(username, newScore):
file = open("Login.txt", "r")
lines = file.readlines()
file.close()
file = open("Login.txt", "w")
for line in lines:
data = line.split(",")
if data[0] == username:
data[2] = str(newScore) + "\n"
file.write(",".join(data))
else:
file.write(line)
file.close()