Python高效管理JSON文件:读写、更新、删除全攻略

liftword3个月前 (02-04)技术文章28

引言:

代码对 JSON 文件的常见操作(读取、写入、追加、删除、更新)的封装,每个方法都对常见的异常情况进行了处理,并且提供了详细的错误提示,失败的原因。

代码封装如下:

import json  #todo 导入json模块用于处理json数据

class JsonFileHandler:
    #todo 初始化函数,传入文件路径作为实例变量
    def __init__(self, file_path):
        self.file_path = file_path  #todo 文件路径存储在实例变量self.file_path中

    #todo 读取json文件并返回内容
    def read_json(self):
        try:
            with open(self.file_path, 'r', encoding='utf-8') as file:  #todo 以读取模式打开文件,确保使用utf-8编码
                data = json.load(file)  #todo 将文件内容加载为Python字典对象
            return data  #todo 返回读取到的数据
        except FileNotFoundError:  #todo 如果文件未找到
            print(f"Error: {self.file_path} not found.")  #todo 输出错误信息
            return None  #todo 返回None表示读取失败
        except json.JSONDecodeError:  #todo 如果文件内容不是有效的json格式
            print(f"Error: {self.file_path} is not a valid JSON file.")  #todo 输出格式错误信息
            return None

    #todo 将数据写入json文件
    def write_json(self, data):
        try:
            with open(self.file_path, 'w', encoding='utf-8') as file:  #todo 以写模式打开文件
                json.dump(data, file, indent=4, ensure_ascii=False)  #todo 将数据写入文件,格式化输出并保留中文字符
            print(f"Data successfully written to {self.file_path}.")  #todo 提示成功写入
        except Exception as e:  #todo 捕获其他可能的异常
            print(f"Error writing to file {self.file_path}: {e}")  #todo 输出异常信息

    #todo 向json文件中追加数据
    def append_to_json(self, data):
        try:
            #todo 打开文件读取数据,如果文件存在则读取,如果文件不存在则创建新文件
            with open(self.file_path, 'r+', encoding='utf-8') as file:
                try:
                    exist_data = json.load(file)  #todo 尝试读取已有数据
                except json.JSONDecodeError:  #todo 如果文件为空或格式错误,初始化为空列表
                    exist_data = []
                exist_data.append(data)  #todo 将新数据添加到已有数据中
                file.seek(0)  #todo 将文件指针移到文件开头
                json.dump(exist_data, file, indent=4, ensure_ascii=False)  #todo 写回数据,格式化输出
                file.truncate()  #todo 截断文件,以确保多余内容被删除
            print(f"Data successfully appended to {self.file_path}.")  #todo 提示成功追加
        except FileNotFoundError:  #todo 如果文件不存在
            with open(self.file_path, 'w', encoding='utf-8') as file:  #todo 创建新文件
                json.dump([data], file, indent=4, ensure_ascii=False)  #todo 将数据写入新文件
            print(f"File not found. New file created and data added to {self.file_path}.")  #todo 提示创建新文件并添加数据

    #todo 从json文件中删除指定的key
    def delete_from_json(self, key):
        try:
            with open(self.file_path, 'r', encoding='utf-8') as file:  #todo 打开文件读取数据
                data = json.load(file)  #todo 读取json数据
        except FileNotFoundError:  #todo 如果文件不存在
            print(f"Error: {self.file_path} not found.")  #todo 输出错误信息
            return
        except json.JSONDecodeError:  #todo 如果文件内容格式错误
            print(f"Error: {self.file_path} is not a valid JSON file.")  #todo 输出格式错误信息
            return

        if key in data:  #todo 如果字典中存在指定的key
            del data[key]  #todo 删除指定的key
            with open(self.file_path, 'w', encoding='utf-8') as file:  #todo 以写模式打开文件
                json.dump(data, file, indent=4, ensure_ascii=False)  #todo 将更新后的数据写回文件
            print(f"Key '{key}' successfully deleted from {self.file_path}.")  #todo 提示成功删除
        else:
            print(f"Key '{key}' not found in the file.")  #todo 如果key不存在,输出提示信息

    #todo 更新json文件中指定key的值
    def update_json(self, key, new_value):
        try:
            with open(self.file_path, 'r', encoding='utf-8') as file:  #todo 打开文件读取数据
                data = json.load(file)  #todo 读取json数据
        except FileNotFoundError:  #todo 如果文件不存在
            print(f"Error: {self.file_path} not found.")  #todo 输出错误信息
            return
        except json.JSONDecodeError:  #todo 如果文件内容格式错误
            print(f"Error: {self.file_path} is not a valid JSON file.")  #todo 输出格式错误信息
            return

        if key in data:  #todo 如果字典中存在指定的key
            data[key] = new_value  #todo 更新该key的值
            with open(self.file_path, 'w', encoding='utf-8') as file:  #todo 以写模式打开文件
                json.dump(data, file, indent=4, ensure_ascii=False)  #todo 将更新后的数据写回文件
            print(f"Key '{key}' successfully updated to '{new_value}'.")  #todo 提示成功更新
        else:
            print(f"Key '{key}' not found in the file.")  #todo 如果key不存在,输出提示信息


#todo 主程序入口
if __name__ == '__main__':
    #todo 示例:初始化JsonFileHandler对象并进行相关操作
    file_path = r"D:\AASEXCHDATE.json"  #todo 定义json文件路径
    json_handler = JsonFileHandler(file_path)  #todo 创建JsonFileHandler实例

    #todo 读取文件内容并输出
    data = json_handler.read_json()
    if data is not None:
        print(data)

    #todo 写入新的数据
    json_handler.write_json(data={'index': 'hello'})

    #todo 追加数据
    json_handler.append_to_json(data={'new_key': 'new_value'})

    #todo 删除指定key的数据
    json_handler.delete_from_json(key='index')

    #todo 更新指定key的数据
    json_handler.update_json(key='new_key', new_value='updated_value')

说明:

其实json文件是可以与之前说过的yaml文件来结合使用的:

JSON 通常用于数据交换,而 YAML 更具可读性,适合配置文件等用途。如果需要在同一个项目中同时使用 JSON 和 YAML 文件,可能是由于不同场景的需求,或者需要将它们结合起来做一些特定的处理。 这个我们后面会出一篇文章来稍微讲解一下

相关文章

Python 中的字典(python中的字典长什么样子)

字典是 Python 中的一种内置数据结构,允许您将数据存储在键值对中。这种类型的数据结构具有高度的通用性,支持基于唯一键高效检索、插入和删除数据。字典非常适合表示结构化数据,其中每个键都可以与特定...

学习编程第197天 python编程pop与popitem方法删除字典数据

今天学习的是刘金玉老师零基础Python教程第92期,主要内容是字典中的删除,pop方法与popitem方法。一、pop方法Pop方法属于字典自带的方法,只需要传入一个参数,这个参数是字典的键,这样就...

Python之容器:字典(dict)就是哈希表换个马甲?

引言从上一篇文章开始,开始了Python中常用的数据结构,也就是容器类的介绍,上一篇文章简要介绍了列表的使用,这一篇文章准备介绍一下Python中字典(dict)的使用。本文的主要内容大概如下:1、简...

python学习笔记:06字典和集合(字典与集合的填空题答案python)

字典定义字典是另一种可变容器模型,且可存储任意类型对象。字典的数据结构为键值对结构{key:value}key必须是唯一的,且是不可变数据类型(如数值、字符串、元组),Value可以是任意类型的数据{...

十二、Python字典的常用方法(python里面字典的用法)

Python字典作为最常用的数据类型之一,是一种特殊的K,V格式的存储结构,Python为它实现了独特的方法。Python常用内置函数len(dict): 计算字典中元素的个数,即键的个数,因为键是不...