0

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 ?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
kAldown
  • 610
  • 2
  • 8
  • 27
  • It is a duplicate. The answer is there if you read it well. "Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. *The size defaults to the current position...*" It only removes what comes after the current file position (in this case the end of the file, so nothing). – mweerden Aug 13 '16 at 10:03
  • @mweerden It is not. That question about `truncate`. What I'm asking - solution for this problem. ok, It such a big confuse for me. So how I suppose to remember content, and then erase a file? – kAldown Aug 13 '16 at 10:07
  • 2
    You probably want to just do a `f.seek(0)` to reset the current position to the start of the file. Then `truncate` and `write` will do what you want. – mweerden Aug 13 '16 at 10:27
  • @mweerden thank you. I'll delete question soon, in case dup. If you want. I may vote for your answer. – kAldown Aug 13 '16 at 10:28
  • 1
    No need to delete it. It might still be helpful even if it is a duplicate. http://meta.stackoverflow.com/questions/265736/should-i-delete-my-question-if-it-is-marked-as-a-duplicate – mweerden Aug 13 '16 at 10:32

0 Answers0