网站首页 > 技术文章 正文
引言:
代码对 JSON 文件的常见操作(读取、写入、追加、删除、更新)的封装,每个方法都对常见的异常情况进行了处理,并且提供了详细的错误提示,失败的原因。
代码封装如下:
Bash
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 文件,可能是由于不同场景的需求,或者需要将它们结合起来做一些特定的处理。 这个我们后面会出一篇文章来稍微讲解一下
猜你喜欢
- 2025-01-06 3分钟教会你用Python读取MySQL中的数据
- 2025-01-06 读取txt、doc、docx、pdf文件——python
- 2025-01-06 20 天学 Python 文件操作:Day 2 深入理解文件读取方法
- 2025-01-06 python 利用python读取DOC文件
- 2025-01-06 一日一技:在Python中逐行读取文件
- 2025-01-06 python中读取图片的6种方式
- 2025-01-06 Python读写docx文件
- 2025-01-06 Python 文件操作全指南:从读写到高级操作
- 2025-01-06 python读取文件
- 2025-01-06 Python如何读写xml
- 06-24Python调用Docker API的使用方式(pycharm docker 调试)
- 06-24青少年Python编程系列28:Python中函数的递归调用
- 06-24python调用sqlite数据库案例(python 调用数据库)
- 06-24【Python机器学习系列】基于Flask来构建API调用机器学习模型服务
- 06-24通过pybind11来实现python调用C++接口(一)
- 06-24Python编程调用Deepseek API创建智能体
- 06-24python多装饰器针对函数、类、方法的调用顺序说明
- 06-24Python Qt GUI设计:Python调用UI文件的两种方法(基础篇—3)
- 270℃Python短文,Python中的嵌套条件语句(六)
- 268℃python笔记:for循环嵌套。end=""的作用,图形打印
- 266℃PythonNet:实现Python与.Net代码相互调用!
- 262℃Python实现字符串小写转大写并写入文件
- 261℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 121℃原来2025是完美的平方年,一起探索六种平方的算吧
- 101℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 96℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- Python调用Docker API的使用方式(pycharm docker 调试)
- 青少年Python编程系列28:Python中函数的递归调用
- python调用sqlite数据库案例(python 调用数据库)
- 【Python机器学习系列】基于Flask来构建API调用机器学习模型服务
- 通过pybind11来实现python调用C++接口(一)
- Python编程调用Deepseek API创建智能体
- python多装饰器针对函数、类、方法的调用顺序说明
- Python Qt GUI设计:Python调用UI文件的两种方法(基础篇—3)
- Python | Django 外部脚本调用 models 数据库
- 自学Python第九天——操作列表(python操作步骤)
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)