Skip to content

Commit a57fc16

Browse files
committed
Only close files if the class opens the file object.
If a file object is passed in, then it is the caller's responsibility to close the file object.
1 parent fa768ae commit a57fc16

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

kerchunk/hdf.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import io
22
import logging
33
import pathlib
4+
from contextlib import ExitStack
45
from typing import Union, Any, Dict, List, Tuple
56

67
import fsspec.core
@@ -103,19 +104,20 @@ def __init__(
103104

104105
# Open HDF5 file in read mode...
105106
lggr.debug(f"HDF5 file: {h5f}")
107+
self._closers = ExitStack()
106108
if isinstance(h5f, (pathlib.Path, str)):
107109
fs, path = fsspec.core.url_to_fs(h5f, **(storage_options or {}))
108-
self.input_file = fs.open(path, "rb")
110+
self.input_file = self._closers.enter_context(fs.open(path, "rb"))
109111
url = h5f
110-
self._h5f = h5py.File(self.input_file, mode="r")
112+
self._h5f = self._closers.enter_context(h5py.File(self.input_file, mode="r"))
111113
elif isinstance(h5f, io.IOBase):
112114
self.input_file = h5f
113-
self._h5f = h5py.File(self.input_file, mode="r")
115+
self._h5f = self._closers.enter_context(h5py.File(self.input_file, mode="r"))
114116
elif isinstance(h5f, (h5py.File, h5py.Group)):
115117
# assume h5py object (File or group/dataset)
116118
self._h5f = h5f
117119
fs, path = fsspec.core.url_to_fs(url, **(storage_options or {}))
118-
self.input_file = fs.open(path, "rb")
120+
self.input_file = self._closers.enter_context(fs.open(path, "rb"))
119121
else:
120122
raise ValueError("type of input `h5f` not recognised")
121123
self.spec = spec
@@ -134,8 +136,7 @@ def __init__(
134136
lggr.debug(f"HDF5 file URI: {self._uri}")
135137

136138
def close(self):
137-
self._h5f.close()
138-
self.input_file.close()
139+
self._closers.close()
139140

140141
def translate(self, preserve_linked_dsets=False):
141142
"""Translate content of one HDF5 file into Zarr storage format.

0 commit comments

Comments
 (0)