Skip to content
Advertisement

extracting info from a text file in python

I am making a system in which when a user plays my game, it compares their score to what they have scored before by using a username and password. the info is stored in text file in the format: score*username*password. I am trying to get those into different variables so that I can check them against other variables. this is the code I’m using. the problem is that the assigning of the variables doesn’t work and I cant work out why

username = "hello"
password = "1234"
player_score = 40

file = open("yahtzee high scores.txt", "r")
lines = file.readlines()
file.close()
highscore = 0
highUser = ""

print(lines)
for line in lines:
    score = ""
    name = ""
    passw = ""
    findingScore = True
    findingName = False
    findingPass = False
    for i in line:
        if i != "*" and findingScore:
            score += i
        elif i != "*" and findingName:
            name += i
        elif i != "*" and findingPass:
            passw += i
        else:
            print(name)
            if findingScore:
                findingName = True
                findingScore = False
            elif findingName:
                findingName = False
                findingPass = True
            elif findingPass:
                findingPass = False
            if int(score) > highscore:

                highscore = int(score)
                highUser = name
                highPass = passw
                print(highscore)
                print(highUser)

Advertisement

Answer

Its much more efficient (and easy) to use json

using the following as file.json

{
    "user1": {"password":"password","high score":50},
    "user2": {"password":"password","high score":30}
}
import json

data = json.load(open('file.json', "r"))

print(data["user1"]["high score"])

#assign new score
data["user1"]["high score"] = 60

# add new user

password = "user3Password123"
score = 30

data["user3"] = {
    "password": password,
    "high score": score
}

json.dump(data, open('file.json', "w"))

the file is now

{
    "user1": {"password":"password","high score":60},
    "user2": {"password":"password","high score":30},
    "user3": {"password": "user3Password123", "high score": 30}

}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement