首页 > 解决方案 > JSON 输出不正确 - Python 项目

问题描述

我必须开发一个程序,在 json 文件中存储一个列表,该列表必须是可读的,以便修改一个元素、删除一个、添加一个等...... json 文件的内容永远不会是正确的,我不明白如何当我添加一个元素时它会改变,所以我的代码一定有问题。

这是我的代码:

import json



class ABC:
    def __init__(self, filename):
        self.__filename = filename
        self.__list = []


        try:
            file=open(self.__filename,"r")
            self.__lista.append(json.load(file))
            print(self.__lista)
        except:
            file=open(self.__filename, "w")
            file.close()
            file = open(self.__filename, "r")


    def add(self, c):
        print(self.__lista)
        self.__lista.append(str(c))
        #print(self.__lista)



    def write_to_json_file(self):
        with open(self.__filename, '+a') as json_file:
            json.dump(self.__lista, json_file, indent=2)
            json_file.write(',')

提前致谢。

标签: pythonjsonpycharm

解决方案


尝试使用+a附加选项打开文件。和__lista = dict()

class Carta:
    def __init__(self, filename):
        self.__filename = filename
        self.__lista = dict()

def add(self, c):
    self.__lista.update(c.__dict__)
    print(self.__lista)
    #print(self.__lista)



def write_to_json_file(self, c):
    with open(self.__filename, 'a') as json_file:
        json.dump(self.__lista, json_file, indent=2)
        json_file.write(',')

请参阅python 文档中的json函数和open函数。


推荐阅读