从python中的文本文件中提取信息

问题描述

我正在开发一个系统,当用户玩我的游戏时,它将使用用户名密码将其分数与之前的分数进行比较。信息以score*username*password格式存储在文本文件中。我试图将它们放入不同的变量中,以便可以对照其他变量进行检查。这是我正在使用的代码。问题是变量的分配不起作用,我无法弄清楚为什么

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)

解决方法

使用json效率更高(更容易)

使用以下内容作为function Get-Folder { Param( $initialDirectory = 17,$message = "Choose a directory" ) $shell = New-Object -ComObject Shell.Application $selection = $shell.browseforfolder(0,$message,65556,$initialDirectory) if($selection){$selection.self.path} } get-folder 'c:\some\pa(th)'

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"))
,

原来有一个函数string.split("*"),该函数会列出其中包含密码和用户名的列表。 ps。不确定split函数的确切语法,但确实存在