summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
authorEric Wieser <wieser.eric@gmail.com>2018-02-08 21:26:34 -0800
committerEric Wieser <wieser.eric@gmail.com>2018-09-23 09:39:54 -0700
commit195881ed6e50085ca8b195c96367748ff3563c53 (patch)
tree1eeb7812b2134a34b85b1d2f7ea1a2f6ff9d4ca2 /numpy
parent8805080acf9e87a10881443c32b57d69fe44aec4 (diff)
downloadnumpy-195881ed6e50085ca8b195c96367748ff3563c53.tar.gz
BUG: Don't leave files open and dangling if np.load has a bad encoding argument, or the file is an invalid zip
Diffstat (limited to 'numpy')
-rw-r--r--numpy/lib/npyio.py27
1 files changed, 14 insertions, 13 deletions
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
index 9a7b244ac..73cf5554a 100644
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -380,16 +380,6 @@ def load(file, mmap_mode=None, allow_pickle=True, fix_imports=True,
memmap([4, 5, 6])
"""
- own_fid = False
- if isinstance(file, basestring):
- fid = open(file, "rb")
- own_fid = True
- elif is_pathlib_path(file):
- fid = file.open("rb")
- own_fid = True
- else:
- fid = file
-
if encoding not in ('ASCII', 'latin1', 'bytes'):
# The 'encoding' value for pickle also affects what encoding
# the serialized binary data of NumPy arrays is loaded
@@ -410,6 +400,17 @@ def load(file, mmap_mode=None, allow_pickle=True, fix_imports=True,
# Nothing to do on Python 2
pickle_kwargs = {}
+ # TODO: Use contextlib.ExitStack once we drop Python 2
+ if isinstance(file, basestring):
+ fid = open(file, "rb")
+ own_fid = True
+ elif is_pathlib_path(file):
+ fid = file.open("rb")
+ own_fid = True
+ else:
+ fid = file
+ own_fid = False
+
try:
# Code to distinguish from NumPy binary files and pickles.
_ZIP_PREFIX = b'PK\x03\x04'
@@ -422,10 +423,10 @@ def load(file, mmap_mode=None, allow_pickle=True, fix_imports=True,
if magic.startswith(_ZIP_PREFIX) or magic.startswith(_ZIP_SUFFIX):
# zip-file (assume .npz)
# Transfer file ownership to NpzFile
- tmp = own_fid
+ ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle,
+ pickle_kwargs=pickle_kwargs)
own_fid = False
- return NpzFile(fid, own_fid=tmp, allow_pickle=allow_pickle,
- pickle_kwargs=pickle_kwargs)
+ return ret
elif magic == format.MAGIC_PREFIX:
# .npy file
if mmap_mode: