程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

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

balukai 2025-01-16 17:56:02 文章精选 8 ℃

引言:

代码对 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 文件,可能是由于不同场景的需求,或者需要将它们结合起来做一些特定的处理。 这个我们后面会出一篇文章来稍微讲解一下

最近发表
标签列表