I am trying to read a json file, modify and then save the modified version.
Unfortunately, the content of the file, instead of being saved, adds another json to the end of the original one.
my code:
with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
test = json.load(test_file)
test['COMPONENTS'] = "test components"
json.dump(test, test_file)
test.json
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}
after running code
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}
expected result:
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}
Please point out what I am doing wrong
My environment
Python 3.10.9
macos 12.3.1
I try to use w+
Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)
StopIteration: 0
During handling of the above exception, another exception occurred:
File "/test.py", line 20, in <module>
test = json.load(test_file)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
2
Answers
I think the problem is adding a
+
to your opening modes. Also note thatw+
would truncate the file, so there will be no JSON to read. I think what you should do is:The easiest way to do it, like UpmostScarab said, is to just open the file twice. If you only want to open it once for some reason, you can read, then
seek(0)
, then write, and finallytruncate
: