I recently had to loop over the messages in a BUFR file and I found the wiki examples very clear but not hugely Pythonic. Instead of something like...
F=open('somefile.bufr','r')
while True:
gid=codes_bufr_new_from_file(F)
if gid is None:
break
... process message gid ...
F.close()
... which isn't exception-safe, what I wanted to write was something like...
for gid in bufr_messages('somefile.bufr'):
... process message gid ...
and have bufr_messages() take care of all the opening and closing of the file and getting and releasing of the messages in an exception-safe way, so I wrote this...
from eccodes import codes_bufr_new_from_file, codes_release
1 Comment
Luke Jones
F=open('somefile.bufr','r')
while True:
gid=codes_bufr_new_from_file(F)
if gid is None:
break
... process message gid ...
F.close()
for gid in bufr_messages('somefile.bufr'):
... process message gid ...
So now if I write...
for gid in bufr_messages('somefile.bufr'):
... I know that if an exception occurs during processing of the message the message will be automatically released and the file automatically closed.