首页 > 解决方案 > 将数据保存在 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)

这个工作文件。但是,当我第二次运行此代码时,它会覆盖文本文件中的现有值。帮助我解决此代码

标签: arraysjsonpython-3.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


推荐阅读