所以我有一個唯一的玩家 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 檔案:

uj5u.com熱心網友回復:
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)
#...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478763.html
上一篇:BashScript如何為用戶名由兩個單詞組成的用戶創建目錄
下一篇:文本檔案到鏈表C
