繁体   English   中英

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

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

所以我有一个唯一的玩家 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()

现在,如果它检测到玩家不是新玩家,它会从 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

问题是,当我在获取数据函数中检查 id 代码时,它会打印出一个空格,就好像 id 代码已更改为空(我无法弄清楚它为什么这样做)并将其打印到终点站:

在此处输入图像描述

playerID JSON 文件:

在此处输入图像描述

如果不重新开始,您将无法两次read()文件。 正确的做法是将文件读入变量:

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