首页 > 解决方案 > 在循环中保存json文件,python

问题描述

在 jupyter notebook 中,我在一个单元格中运行了这段代码:

for i in range(10):
  with open('data.json', 'w') as f:
    json.dump({"counter":i}, f)
  time.sleep(10000)

到目前为止很容易,但是在执行单元之后,在每次迭代期间实际的 data.json 文件不会有任何更新,它会一直更新到程序结束。换句话说,作为文件对象的 data.json 一直保持打开状态,直到代码结束。

如何循环更新磁盘上的文件?

标签: pythonjsonloopssave

解决方案


json模块不能以这种方式工作 AFAIK。您必须将 json 数据加载到字典/列表中,然后进行更改,然后再次写入文件:

# funciton to read json files
def read_json(path):
    with open(path, 'r') as file:
        return json.load(file)

# function to write json files
def write_json(path, data, indent=4):
    with open(path, 'w') as file: 
        json.dump(data, file, indent=indent) 

# read some json data
json_data = read_json('./my_json_file.json')

# ... do some stuff to the data

# write the data back to the file
write_json('./my_json_file.json', json_data)

推荐阅读