89 lines
3.2 KiB
Python
89 lines
3.2 KiB
Python
#!/usr/bin/python3
|
||
# -*- coding: UTF-8 -*-
|
||
# 设置utf-8 显示中文
|
||
"""
|
||
@Author: guo
|
||
@File:handle_jsonfile.py
|
||
"""
|
||
import json
|
||
import os
|
||
|
||
|
||
class HandleJsonFile:
|
||
'''
|
||
操作json文件,进行读写.
|
||
'''
|
||
|
||
def write_json_data(self, filepath, dict_value:dict):
|
||
'''
|
||
将dict转为string后,写入到json文件中,易传输 \n
|
||
:param filepath: 文件路径,包含文件名
|
||
:param dict_value: 要写入的字典值
|
||
:return: None
|
||
'''
|
||
filepath = filepath
|
||
# 判断是否是以.josn结束
|
||
if filepath:
|
||
filepath = filepath if filepath.endswith('.json') else filepath + '.json'
|
||
|
||
# 在写入之前,要先检测目录是否存在,若不存在,则新建,否则会抛异常
|
||
dir = os.path.dirname(filepath)
|
||
if not os.path.exists(dir):
|
||
# os.mkdir(dir)
|
||
os.makedirs(dir, exist_ok=True)
|
||
|
||
with open(filepath, 'w', encoding='utf-8') as fp:
|
||
# dict 转化为string 并存入到json文件中,要设置不启用askii编码,否则中文会显示编码。
|
||
fp.write(json.dumps(dict_value, ensure_ascii=False))
|
||
|
||
def write_dict_to_json_file(self, filepath, dict_value:dict):
|
||
'''
|
||
将dict写入到json文件中(将dict转化为json字符串格式,写入文件) ,易存储 \n
|
||
:param filepath: 文件路径
|
||
:param dict_value: 要写入的字典
|
||
:return:
|
||
'''
|
||
filepath = filepath
|
||
# 判断是否是以.josn结束
|
||
if filepath:
|
||
filepath = filepath if filepath.endswith('.json') else filepath + '.json'
|
||
|
||
# 在写入之前,要先检测目录是否存在,若不存在,则新建,否则会抛异常
|
||
dir = os.path.dirname(filepath)
|
||
if not os.path.exists(dir):
|
||
# os.mkdir(dir)
|
||
os.makedirs(dir, exist_ok=True)
|
||
|
||
with open(filepath, 'w', encoding='utf-8') as fp:
|
||
# 直接将字典写入到json文件中,要设置不启用askii编码,否则中文会显示编码。
|
||
json.dump(dict_value, fp, ensure_ascii=False)
|
||
|
||
def read_json_data(self, filepath):
|
||
'''
|
||
读取json文件中的值,并转化为dict,针对内存对象,将string转化为dict对象 \n
|
||
:param filepath: 文件相对路径,包含文件名
|
||
:return: 转化后的dict
|
||
'''
|
||
filepath = filepath
|
||
# 判断是否是以.josn结束
|
||
if filepath:
|
||
filepath = filepath if filepath.endswith('.json') else filepath + '.json'
|
||
|
||
with open(filepath, 'r', encoding='utf-8') as fp:
|
||
# 将string转化为dict
|
||
return json.loads(fp.read())
|
||
|
||
def read_json_file_to_dict(self, filepath):
|
||
'''
|
||
读取json文件,并将数据转化为dict,针对文件句柄,是直接从文件中读取 \n
|
||
:param filepath: 文件的相对路径,包含文件名
|
||
:return: 转化后的dict
|
||
'''
|
||
filepath = filepath
|
||
# 判断是否是以.josn结束
|
||
if filepath:
|
||
filepath = filepath if filepath.endswith('.json') else filepath + '.json'
|
||
|
||
with open(filepath, 'r', encoding='utf-8') as fp:
|
||
return json.load(fp)
|