-2

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()

Data.json showing nothing.

Other info:
Environment: VSCode
Python version: 3.9.0
Library: json (import json)
Called: inside a thread.
No errors.

coderman1234
  • 210
  • 3
  • 12
  • 2
    Cloud you share full example? P.S. why "data.json" in your path is repeated twice? – user3431635 Mar 06 '21 at 15:21
  • The second time is just for the reading. That was for debugging. The main stuff is the first call. @user3431635 – coderman1234 Mar 06 '21 at 15:21
  • @user3431635 I iedited the post so that all the code is visible. – coderman1234 Mar 06 '21 at 15:24
  • json.dump assumed to dump object, so why you use str(db)? – user3431635 Mar 06 '21 at 15:25
  • another thing I tried to show the data. I'll remove it. @user3431635 – coderman1234 Mar 06 '21 at 15:26
  • 1
    So how you db looks like? Cloud you give full example as I have asked in my first comment? – user3431635 Mar 06 '21 at 15:27
  • Please [edit] your question to provide a [mcve]; this should also detail how the content is read. The code snippets shown are not complete and contain at least one syntax error and one type error. – MisterMiyagi Mar 06 '21 at 15:33
  • Note that opening a file for writing may truncate it *immediately*, and writes may be delayed until the end of a context manager. In short, seeing how the ``while True:`` loop immediately re-opens the file after the context manager, content may exist for only a split second. – MisterMiyagi Mar 06 '21 at 15:37

1 Answers1

0

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

user3431635
  • 372
  • 1
  • 7
  • sure. It works fine on my side. (you have to add import json, from time import sleep , from threading import Thread, and db = {'aaaa': 'bbbb'} lines – user3431635 Mar 06 '21 at 17:12
  • So I will paste whole code. Please point me out what sintax error it gives on your side. – user3431635 Mar 06 '21 at 17:47