簡體   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