How to iterate over directory of grib2 files with pygrib?

268 views Asked by At

So I'm working on a research project where I have about 6500 HRRR .grib2 files in a directory and all I need to do is simply open each grib2 file and print the the messages into a .txt for later parsing of values. Dont worry, I have cut down the normally large .grib2 files from about 150-300mb to on average 4.5mb so i'm not too worried about memory errors.

Here is the code i'm working with so far:

import pygrib, sys
import numpy as np
import os

station_lat=41.31190
station_lon=-95.90185
print("INPUT LAT LON: ",station_lat,station_lon)

path = "/Volumes/harddrive/HRRRFILES"
gribfiles = os.listdir("/Volumes/harddrive/HRRRFILES")

for file in gribfiles:
    if file.endswith(".grib2"): #iterate files with .grib2 appendage
        grbs = pygrib.open(gribfiles) 
        for grb in grbs:
            lats, lons = grb.latlons()
            print("\n",grb.messagenumber,grb) # For Debugging Purposes

            a = abs(lats-station_lat)+abs(lons-station_lon)

            lat_counter,lon_counter = np.unravel_index(a.argmin(),a.shape)
            data=grb.values[lat_counter,lon_counter]

            print(lat_counter,lon_counter,lats[lat_counter,lon_counter],lons[lat_counter,lon_counter],data)

Although when I run this I get the following error:

INPUT LAT LON:  41.3119 -95.90185
Traceback (most recent call last):
  File "example1.py", line 15, in <module>
    grbs = pygrib.open(gribfiles) 
  File "pygrib.pyx", line 393, in pygrib.open.__cinit__
TypeError: expected bytes, list found

Some help would be super appreciated.

0

There are 0 answers