网站首页 > 文章精选 正文
引言:
代码对 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散装笔记——20: 列表(3)
猜你喜欢
- 2025-01-16 一文了解 Python 列表
- 2025-01-16 Python学习笔记——列表
- 2025-01-16 Python中list列表函数用法大全(思维脑图加详细解读)
- 2025-01-16 Python教程:列表的排序操作
- 2025-01-16 2 常见的Python数据结构-元组、列表
- 2025-01-16 一篇文章带你弄懂Python基础之列表介绍和循环遍历
- 2025-01-16 Python之容器:列表是个百宝箱,什么都能往里装
- 2025-01-16 Python 列表生成式全解
- 2025-01-16 python散装笔记——17: 数组
- 2025-01-16 Python中的列表和元组,你了解多少?
- 05-16一文学完《图解HTTP》
- 05-16您未被授权查看该页
- 05-16快码住!带你十分钟搞懂HTTP与HTTPS协议及请求的区别
- 05-16一张图带你了解HTTP 9个请求方法,收藏!
- 05-16Java 里的基本类型和引用类型
- 05-16新手小白学Java|零基础入门笔记|原来学Java可以这么简单
- 05-16深度学习CV方向高频算法面试题6道|含解析
- 05-16C语言结构体成员变量名后加冒号和数字的含义
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)