I'm trying to update content of file. That is what I do:
with open('test.txt', 'r+') as f:
content = json.loads(f.read())
f.truncate()
content['key'] = 'new value'
f.write(json.dumps(content))
What do I expect:
# test.txt
{'key': 'old value'}
func()
# test.txt
{'key': 'new value'}
But what I've got:
{'key': 'old value'}{'key': 'new value'}
P.S. I vote that this is not a duplicate.
After calling f.read()
, I'm on the end of a file, so f.truncate()
should erase whole file, but it isn't.
Or am I wrong ?