自学内容网 自学内容网

Python批量读取mat文件

一、前言

使用Python中的h5py库实现同一目录下多个mat文件的批量读取功能,获取数据、lon、lat等信息,其他变量内容可根据自己的mat格式进行更改。

二、代码

def open_matfiles(dir, start_index=None, end_index=None,lev_index=None,lev_value=None):
    '''
    打开一个文件夹下的所有mat文件,并返回数据、经度、纬度和层次信息。

    参数:
    dir (str): 包含.mat文件的文件夹路径。
    start_index (int, 可选): 要读取的第一个文件的索引(默认是0)。
    end_index (int, 可选): 要读取的最后一个文件的索引(默认是所有文件)。
    lev_index (int, 可选): 要读取的特定层次的索引(默认是None,表示读取所有层次)。
    lev_value (float, 可选): 要读取的特定层次的值(默认是None,表示读取所有层次),针对GPH200、500。

    返回:
    tuple: 包含以下元素的元组:
        - data (numpy.ndarray): 读取的所有数据。
        - lon (numpy.ndarray): 经度信息。
        - lat (numpy.ndarray): 纬度信息。
        - lev (numpy.ndarray): 层次信息(如果存在)。

    异常:
    FileNotFoundError: 如果指定的文件夹不存在。
    '''
    
    import h5py
    import numpy as np
    from pathlib import Path

    dir_path = Path(dir)
    if not dir_path.exists():
        raise FileNotFoundError(f"文件夹{dir}不存在")
    
    mat_files = sorted(dir_path.glob("*.mat"))  # 对文件进行排序
    
    if start_index is None:
        start_index = 0
    if end_index is None:
        end_index = len(mat_files)
    
    lon = None
    lat = None
    lev = None
    data_list = []
    

    for mat_file in mat_files[start_index:end_index]:
        with h5py.File(mat_file, "r") as mat_data:
            if lon is None:
                lon = np.array(mat_data["lon"])
            if lat is None:
                lat = np.array(mat_data["lat"])
            if lev is None:
                lev = np.array(mat_data.get("lev", None))  # 使用get方法提供默认值
            
            if lev is not None and lev_index is not None:
                data = np.array(mat_data["data"])[...,lev_index,:,:] # lev在倒数第三层
                data_list.append(data)
            elif lev is not None and lev_value is not None:
                index = np.where(lev == lev_value)
                data = np.array(mat_data["data"])[...,index,:,:]
                data_list.append(data)
            else:
                data = np.array(mat_data["data"])
                data_list.append(data)
    
    data = np.stack(data_list, axis=0)

    return data, lon, lat, lev


原文地址:https://blog.csdn.net/qq_41857385/article/details/142763413

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!