Home > Net >  Why is this python function not reading my json File string properly?
Why is this python function not reading my json File string properly?

Time:05-20

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.

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

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:

enter image description here

The playerID JSON File:

enter image description here

CodePudding user response:

You can't read() a file twice without seeking back to the start. 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)
#...
  • Related