Based on the code you provided, and what you are trying to do (return the file cursor back to the beginning of the file), you are not actually doing that with f.truncate. You are actually truncating your file. i.e. Clearing the file entirely.
Per the help on the truncate method:
truncate(...) truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
What you are actually looking to do with returning the cursor back to the beginning of the file is using seek.
The help on seek:
seek(...) seek(offset[, whence]) -> None. Move to new file position.
So, explicitly, to get back to the beginning of the file you want f.seek(0).
For the sake of providing an example of what is happening. Here is what happens with truncate:
File has stuff in it:
>>> with open('v.txt') as f: ... res = f.read() ... >>> print(res) 1 2 3 4
Call truncate and see that file will now be empty:
>>> with open('v.txt', 'r+') as f: ... f.truncate(0) ... 0 >>> with open('v.txt', 'r') as f: ... res = f.read() ... >>> print(res) >>>
Using f.seek(0):
>>> with open('v.txt') as f: ... print(f.read()) ... print(f.read()) ... f.seek(0) ... print(f.read()) ... 1 2 3 4 0 1 2 3 4 >>>
The long gap between the first output shows the cursor at the end of the file. Then we call the f.seek(0) (the 0 output is from the f.seek(0) call) and output our f.read().
{}. The script did perform the expected modifications and stored the correct JSON string back to the file (without a newline at the end.)f.truncateclears the file, it does not return your file cursor back to the beginning of the file. If you are looking to bring the cursor back to the beginning of the file you are looking forf.seek(0).