Close an open h5py data file

前端 未结 3 2066
北海茫月
北海茫月 2020-12-31 00:49

In our lab we store our data in hdf5 files trough the python package h5py.

At the beginning of an experiment we create an hdf5

3条回答
  •  一个人的身影
    2020-12-31 01:51

    This is how it could be done (I could not figure out how to check for closed-ness of the file without exceptions, maybe you will find):

    import gc
    for obj in gc.get_objects():   # Browse through ALL objects
        if isinstance(obj, h5py.File):   # Just HDF5 files
            try:
                obj.close()
            except:
                pass # Was already closed
    

    Another idea:

    Dpending how you use the files, what about using the context manager and the with keyword like this?

    with h5py.File("some_path.h5") as f:
       f["data1"] = some_data
    

    When the program flow exits the with-block, the file is closed regardless of what happens, including exceptions etc.

提交回复
热议问题