記錄一下使用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