import pickle
import yaml
import scipy.io as scio
import numpy as np
import os
from typing import Union, List


def load_pkl(filename):
    with open(filename, "rb") as fr:
        data = pickle.load(fr, encoding="latin1")
    return data


def load_yaml(filename):
    with open(filename, "rb") as fr:
        data = yaml.load(fr, Loader=yaml.CLoader)
    return data


def load_mat(filename):
    return scio.loadmat(filename)


def load_npz(filename):
    """print(data.files)"""
    return np.load(filename, allow_pickle=True)


def load_npy(filename):
    return np.load(filename, allow_pickle=True)


def load_txt(filename: str) -> str:
    with open(filename, "r") as fr:
        lines = fr.readlines()
    return "".join(lines)


def save_txt(filename: str, text: Union[str, List[str]]):
    with open(filename, "w") as fw:
        if isinstance(text, str):
            fw.write(text)
        else:
            fw.write("\n".join(text))


def save_yaml(filename, data):
    with open(filename, "w", encoding="utf-8") as fw:
        yaml.dump(data, fw)


def find_all_file(folder: str):
    """遍历文件夹下所有文件(支持多级目录)"""
    for root, ds, fs in os.walk(folder):
        for f in fs:
            fullname = os.path.join(root, f)
            yield fullname
