diff options
author | Matti Picus <matti.picus@gmail.com> | 2021-08-26 17:02:49 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-08-26 17:02:49 +0300 |
commit | 63a10fd53066d86a18831a2c0091f34de46c45a0 (patch) | |
tree | 891bee5f50e089a383aae45e9797796557abcea9 /numpy/lib/npyio.py | |
parent | f0c3c34086d5d97ecd0845d8aec33cc9dd5c1e33 (diff) | |
parent | 14dc7d84adbfafd994d87da47170796f527af09d (diff) | |
download | numpy-63a10fd53066d86a18831a2c0091f34de46c45a0.tar.gz |
Merge pull request #19725 from anntzer/loadtxt-fh-closing
MAINT: Use a contextmanager to ensure loadtxt closes the input file.
Diffstat (limited to 'numpy/lib/npyio.py')
-rw-r--r-- | numpy/lib/npyio.py | 26 |
1 files changed, 12 insertions, 14 deletions
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index dfcb07d4f..6f2a211b6 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -1033,7 +1033,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, dtype_types, packer = _loadtxt_flatten_dtype_internal(dtype) - fown = False + fh_closing_ctx = contextlib.nullcontext() try: if isinstance(fname, os_PathLike): fname = os_fspath(fname) @@ -1041,7 +1041,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, fh = np.lib._datasource.open(fname, 'rt', encoding=encoding) fencoding = getattr(fh, 'encoding', 'latin1') line_iter = iter(fh) - fown = True + fh_closing_ctx = contextlib.closing(fh) else: line_iter = iter(fname) fencoding = getattr(fname, 'encoding', 'latin1') @@ -1064,16 +1064,17 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, f"or generator. Got {type(fname)} instead." ) from e - # input may be a python2 io stream - if encoding is not None: - fencoding = encoding - # we must assume local encoding - # TODO emit portability warning? - elif fencoding is None: - import locale - fencoding = locale.getpreferredencoding() + with fh_closing_ctx: + + # input may be a python2 io stream + if encoding is not None: + fencoding = encoding + # we must assume local encoding + # TODO emit portability warning? + elif fencoding is None: + import locale + fencoding = locale.getpreferredencoding() - try: # Skip the first `skiprows` lines for i in range(skiprows): next(line_iter) @@ -1170,9 +1171,6 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, nshape[0] += len(chunk) X.resize(nshape, refcheck=False) X[pos:, ...] = chunk - finally: - if fown: - fh.close() if X is None: X = np.array([], dtype) |