Search code examples
pythonh5pycontextmanager

Does the h5py file context manager automatically close files?


I've been using f = h5py.File(filename, 'r') for a while, and it requires closing with f.close() at the end.

Recently I discovered that I can do:

with h5py.File(filename, 'r') as f:
     # code to manipulate the file

However I'm not sure: Does this "context manager" (as they call it on their page) automatically close the file or do I still have to add f.close() at the end?

I tried to find the answer in the docs, but the context manager is only mentioned in a one-liner during the Quickstart guide and apparently no further info about it is there.


Solution

  • The answer is: Yes, the context manager automatically closes the file.