json.dump 没有转储任何东西,给我留下一个空文件 | Python

json.dump doesn't dump anything, and leaves me with an empty file | Python

我一直在尝试使用 json 库将字典转储到我的 JSON 文件中。但是,当我转储时,文件中没有显示任何内容。此外,当我读取文件时(使用 open('file').read()),它会在那里显示数据!谁能帮我找到这个幻影数据?

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

其他信息:
环境:VSCode
Python版本:3.9.0
图书馆:json(导入json)
调用:线程内。
没有错误。

正确代码:

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

在您的情况下,数据被写入(刷新)到文件中,并立即重新打开文件进行写入。我已将 sleep 从“with”语句移开,现在可以使用了