python - 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(',')
提前致谢。
解决方案
尝试使用+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
函数。
推荐阅读
- angular - 点击离子行
- kubernetes - AKS 中的负载平衡器服务现在正在运行。请看截图
- ruby - gitlab捆绑安装时re2.cc编译问题
- html - 使用长 HTML 的 Node.JS Nodemailer
- javascript - Webpack 混淆器标识符已经被声明
- tcl - tcl foreach 行在空格2上拆分
- javascript - 通过在 react redux 中调用没有页面重新加载的函数来调度动作和重定向(页面重新加载问题)
- json - 无法获取 Amazon S3 文件的内容并使用 python 和 boto3 编辑该文件
- python - 如何在python中构建maxHeap
- python-3.x - 如何用不带双引号的字符串替换列表元素?