You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python全内存从URL读取压缩GRIB文件至xarray数据集的方法

内存中读取远程gzipped GRIB2文件为Xarray Dataset

单个文件读取

你已经完成了下载和解压到内存的步骤,接下来只需将解压后的二进制数据传入Xarray的open_dataset,并指定GRIB文件对应的引擎cfgrib即可。

完整代码

import urllib.request
import io
import gzip
import xarray as xr

URL = 'https://mtarchive.geol.iastate.edu/2022/12/24/mrms/ncep/SeamlessHSR/SeamlessHSR_00.00_20221224-000000.grib2.gz'

# 下载压缩文件并在内存中解压
response = urllib.request.urlopen(URL)
compressed_buffer = io.BytesIO(response.read())
with gzip.GzipFile(fileobj=compressed_buffer, mode='rb') as gz_file:
    decompressed_buffer = io.BytesIO(gz_file.read())

# 读取为Xarray Dataset
ds = xr.open_dataset(decompressed_buffer, engine='cfgrib')
print(ds)

依赖说明

需要提前安装必要库:

pip install xarray cfgrib

批量读取目录下所有文件

要实现类似open_mfdataset的批量读取,需要先获取目录下所有目标文件的URL,再逐个读取后合并。

完整代码

import urllib.request
from bs4 import BeautifulSoup
import io
import gzip
import xarray as xr

# 目标目录URL
base_dir_url = 'https://mtarchive.geol.iastate.edu/2022/12/24/mrms/ncep/SeamlessHSR/'

# 1. 爬取目录页面,提取所有.grib2.gz文件的完整URL
response = urllib.request.urlopen(base_dir_url)
soup = BeautifulSoup(response.text, 'html.parser')
file_urls = [
    base_dir_url + a_tag['href']
    for a_tag in soup.find_all('a')
    if a_tag['href'].endswith('.grib2.gz')
]

# 2. 定义内存读取单个远程GRIB文件的函数
def load_remote_grib(url):
    response = urllib.request.urlopen(url)
    compressed_data = io.BytesIO(response.read())
    with gzip.GzipFile(fileobj=compressed_data, mode='rb') as gz_file:
        decompressed_data = io.BytesIO(gz_file.read())
    return xr.open_dataset(decompressed_data, engine='cfgrib')

# 3. 批量读取并合并数据集
# 若文件按时间序列命名,可按time维度合并,需根据实际数据结构调整
dataset_list = [load_remote_grib(url) for url in file_urls]
combined_ds = xr.concat(dataset_list, dim='time', combine='nested')

print(combined_ds)

额外依赖

需安装解析HTML的库:

pip install beautifulsoup4

注意事项

  • 若合并时出现维度不匹配,需检查每个数据集的维度信息,调整concat的参数(如指定dim为实际存在的维度)
  • 若目录下文件数量过多,一次性全部加载会占用大量内存,建议分批次处理或按需筛选文件

内容的提问来源于stack exchange,提问作者hm8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:20:31