arrays - 将数据保存在 json 文件中而不覆盖 python 中的现有文件
问题描述
我需要在 json 文件中添加数据而不覆盖。
我使用的代码是:
import json
data=[]
def arr():
x=0
while x<1:
print(x)
x-=1
X.append(x)
data.update(x)
with open('x.txt','w')as outfile:
json.dump(data,outfile)
arr()
print(X)
这个工作文件。但是,当我第二次运行此代码时,它会覆盖文本文件中的现有值。帮助我解决此代码
解决方案
如果要在每次运行此代码时将数据追加到文件中,则需要使用追加模式。
你的代码:
with open('x.txt','w')as outfile:
应该
with open('x.txt','a')as outfile:
'w'
模式(或写入模式)将使您覆盖文件,而模式'a'
(或附加模式)将使您将数据附加到文件中。
在此处了解更多信息: https ://www.w3schools.com/python/python_file_write.asp
推荐阅读
- rest - 如何扩展 acumatica api 以在销售订单行项目中附加文件
- python - 在 sklearn 中使用自定义距离度量进行聚类
- php - 如何将复选框输入数据库
- hibernate - 使用嵌套集休眠
- reactjs - 为什么数组没有在反应中使用useState设置
- ios - React Navigation 应用程序在发布模式下或通过 ios 上的 ipa 崩溃,但在调试模式下工作正常
- spring - Spring Boot 无法以 aws starter 依赖项启动
- three.js - 如何在服务器端加载 json 模型?
- haskell - 显示前面带有“+”号的数字
- amazon-web-services - 无法通过 Java 代码访问 S3。[但可以通过 AWS CLI]