I have been trying to dump a dictionary into my JSON file with the json
library. However, when I dump, the file doesn't show anything inside it. Furthermore, when I read the file (using open('file').read()
), it shows the data there! Can anyone help me locate this phantom data?
db = {'aaaa': 'bbbb'} # This is just for testing, but the shape of the actual DB will be about the same.
def write()
while True:
with open('C:\\Users\\very\\long\\path\\to\\json-file\\data.json', 'w') as f:
json.dump(db, f)
sleep(2)
print('dumped')
Thread(target=write()).start()
Other info:
Environment: VSCode
Python version: 3.9.0
Library: json (import json)
Called: inside a thread.
No errors.
Correct code:
import json
from time import sleep
from threading import Thread
db = {'aaaa': 'bbbb'}
def write():
while True:
with open('data2.json', 'w') as f:
json.dump(db, f)
print('dumped')
sleep(10)
Thread(target=write()).start()
In your case, data is written (flushed) into the file and instantly file is reopened for writing. I have moved sleep from "with" statment and now it works