简体   繁体   English

为什么这个 python 函数不能正确读取我的 json 文件字符串?

[英]Why is this python function not reading my json File string properly?

So I have a unique player ID string that is stored in a JSON file after it detects on start-up that the player is new to the game.所以我有一个唯一的玩家 ID 字符串,它在启动时检测到玩家是游戏新手后存储在 JSON 文件中。

def checkIfPlayerIsNew():

    if os.path.exists("myJson.json"):
        print('file exists')

        k = open('myPlayerIDs.json')
        print(k.read())
        #print("This is the k value: {}".format(code))
        #code = json.dumps(k)

        getData(k.read())

    else:
        print('file does not exist')

        f = open('myJson.json', 'x')  #creates the file if it doesn't exist already
        f.close()

        file = open('myPlayerIDs.json', 'w')
        file.write(json.dumps(str(uuid.uuid4())))
        file.close

        checkIfPlayerIsNew()

Now, if it detects that the player is not new it gets the ID from the JSON File and passes it to the get data function below现在,如果它检测到玩家不是新玩家,它会从 JSON 文件中获取 ID 并将其传递给下面的获取数据函数

def getData(idCode = "X"):

    print('the id code is this: {}'.format(idCode))
    outputFile = json.load(open('myJson.json')) 
    for majorkey, subdict in outputFile.items():
        if majorkey == idCode: 
            for subkey, value in subdict.items():
                print('{} = {}'.format(subkey, value))
                #playerData[subkey] = value
        else:
            print("ID Does not match") 
            break

The problem is that when I check the id code in the get data function it prints out a blank space as if the id code has been changed to nothing (which I can't figure out why it has done that) and prints this out to the terminal:问题是,当我在获取数据函数中检查 id 代码时,它会打印出一个空格,就好像 id 代码已更改为空(我无法弄清楚它为什么这样做)并将其打印到终点站:

在此处输入图像描述

The playerID JSON File: playerID JSON 文件:

在此处输入图像描述

You can't read() a file twice without seeking back to the start.如果不重新开始,您将无法两次read()文件。 The right thing to do here is to read the file into a variable:正确的做法是将文件读入变量:

if os.path.exists("myJson.json"):
    print('file exists')

    # Read file into a variable and use it twice
    with open('myPlayerIDs.json', 'r') as k:
        data = k.read()

    print(data)
    getData(data)
#...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM