常见数据读写

import json
import yaml
import pickle
import ruamel.yaml

def read_txt(path: str):
	with open(path, 'r') as f:
		return f.readlines()

def save_txt(obj, path: str):
	with open(path, 'w') as f:
		f.writelines(obj)

def read_json(path: str):
    with open(path, encoding='utf-8') as fp:
        return json.load(fp)

# obj被存储的文件
def save_json(obj, path: str, indent: int=4):
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    with open(path, 'w') as fp:
        json.dump(obj, fp, indent=indent)

def read_pkl(pkl_path: str):
    with open(pkl_path, 'rb') as fp:
        return pickle.load(fp)

def save_pkl(obj, path:str):
    with open(path, "wb") as f:
        pickle.dump(obj, f)

def read_Yaml(file):  # -> Union[dict, list, None]:
    with open(file, 'r', encoding='utf-8') as f:
        return yaml.load(f, yaml.Loader)

def create_Yaml(file, data: dict):
    with open(file, 'w', encoding='utf-8') as f:
        writer = ruamel.yaml.YAML()
        writer.indent(mapping=2, sequence=4, offset=2)
        writer.dump(data, f)

你可能感兴趣的:(Python,json,python)