python - 在循环中保存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 一直保持打开状态,直到代码结束。
如何循环更新磁盘上的文件?
解决方案
该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)
推荐阅读
- ffmpeg - 将图像编码为 h264 和 rtp 输出:没有 sprop-parameter-sets 的 SDP 文件无法播放
- snowflake-cloud-data-platform - 在 Snowflake 中重新创建管道时保留负载历史记录
- java - 对 DynamoDB 表进行排序的任何合理方法?
- c# - Google.Cloud.Firestore HttpRequestException 使我的应用程序崩溃
- c# - Microsoft.FeatureManagement.FeatureManager 未检索到带有标签的 Azure 应用程序配置功能标志
- python - 如何在没有 python 集合的 tensorflow 循环中使用“追加”?
- javascript - 如果我在 HTML 元素上有一个事件侦听器,当有多个子元素时,如何获取我单击的子元素的值
- c++ - 可以使用模板进行 consteval 吗?
- svm - 如何在 Weka 中构建 SVM 分类器以仅考虑数据集中的某些特征?
- r - 使用 lapply 向数据框添加行