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, you want to be sure you close files when you’re done with them.
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 upop exiting the indent.
There are rare edge cases where you do need to keep the handle open without context manager, but you should typically instead close and reopen the file.