Why use h5py context manager?

Using a context manager when working with file I/O in Python helps avoid exceeding resource limits. Particularly when doing long batch run jobs, whether on your PC, HPCC or supercomputer, be sure you close files after use–context managers do this automatically and efficiently.

File I/O example context manager

import h5py
from pathlib import Path()

fn = Path('~/mydir/myfile).expanduser()

with fn.open('r') as f:
    line = f.readline()

with h5py.File('~/mydir/myfile.h5','r') as f:
    data = f['/myvar']

In both the text file case and HDF5 case, the file is closed upon exiting the indent.

There are edge cases where you do need to keep the handle open without context manager, but you should typically instead close and reopen the file.

Leave a Comment