记录一下使用xarray读取hdf4(not hdf5)过程中遇到的问题.
- 目的: 读取hdf4 file的matadata
- 遇到的问题:使用xarray.open_dataset()失败
- 解决方法:使用pyhdf.SD代替
import os
from pyhdf.SD import SD, SDC
import xarray as xr
import numpy as np
import pandas as pd
import datetime as dt
import hvplot.xarray
import scipy
import pprint
import warnings
warnings.filterwarnings('ignore')# 输入文件
file ='xxx.hdf' (ps:这里是hdf文件,not hdf5,没有试过hdf5是否成功)# --------方法1: 失败-------
# --------方法1: 失败-------
ds = xr.open_dataset(file,engine='pynio')
metadata = ds.attrs[attr_name]//e.g., attr_name = 'StructMetadata.0'主要的原因:
for reading GRIB and other geoscience specific file formats.
Note that PyNIO is not available for Windows and
that the PyNIO backend may be moved outside of xarray in the future.# --------方法2: 成功-------
# --------方法2: 成功-------
ds = SD(file, SDC.READ)
all_metadata = ds.attributes()
specific_metadata = getattr(ds, attr_name) //attr_name为想要读取变量的name,比如’temperature'
参考
[1] 使用rioxarray读取hdf: link
[2] 使用rioxarray读取hdf: link
[3] 使用pyhdf读取hdf: link
[4] 使用pyhdf读取hdf metadata: link
[5] pyhio: link
[6] pyhio: link