0

I came across the following problem, the code example below is returning a curly bracket too much every second call:

import json as js
def switchState(path, type):
    file = open(path + '/states.txt', 'r+')
    json = js.loads(file.read())
    json[type] = not json[type]
    file.seek(0)
    js.dump(json, file)
    file.close()

in whereas the data json has the form

{"sim": true, "pip": false}

, and calling

switchState('path','sim')

once, leads to

{"sim": false, "pip": false}

but calling it a second time it leads to:

{"sim": true, "pip": false}}

anyone has an idea whats the reason for this? thanks in advance

Asel
  • 15
  • 3

1 Answers1

0

First I suggest using the with statement as a context manager is easier than manually closing and more suggested. Second the reason this is happening is because the second time the text is shorter therefore the extra text that wasn't overwritten. Just overwrite the file as this seems to be the only data in it.

def switchState(path, type):
    with open(path + '/states.txt') as infile:
        json = js.load(file)
    json[type] = not json[type]
    with open(path + '/states.txt', 'w') as infile:
        js.dump(json, file)
    
Jab
  • 26,853
  • 21
  • 75
  • 114