【问题标题】:save json file within a loop, python在循环中保存json文件,python
【发布时间】:2021-01-15 15:21:45
【问题描述】:

在 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 作为文件对象在代码结束前一直保持打开状态。

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

【问题讨论】:

    标签: python json loops save


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 2016-01-31
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多