我已經從這個列表中下載了一個文件https://opendata.dwd.de/weather/nwp/icon-eu/grib/03/t_2m/(實際文件名每天都會變化),它們是 bz2 壓縮的。我可以使用例如讀取解壓縮的文件import xarray as xr# cfgrib + dependencies are also requiredgrib1 = xr.open_dataset("icon-eu_europe_regular-lat-lon_single-level_2020101212_001_ASHFL_S.grib2", engine='cfgrib')但是,我想讀入壓縮文件。我嘗試過類似的事情with bz2.open("icon-eu_europe_regular-lat-lon_single-level_2020101818_002_ASWDIFD_S.grib2.bz2", "rb") as f: xr.open_dataset(f, engine='cfgrib')但這不起作用。我正在尋找任何以編程方式讀取壓縮文件的方法。
1 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
我在處理數值天氣預報數據時遇到了同樣的問題。
我在這里所做的是下載文件并將其保存為二進制對象(例如使用urlopen或requests)。將此對象傳遞給以下函數:
import bz2, shutil
from io import BytesIO
from pathlib import Path
def bunzip_store(file: BytesIO, local_intermediate_file: Path):
with bz2.BZ2File(file) as fr, local_intermediate_file.open(mode="wb") as fw:
shutil.copyfileobj(fr, fw)
解壓后的文件將存儲在local_intermediate_file. 現在您應該能夠打開該文件。
添加回答
舉報
0/150
提交
取消