numpy.lib.npyio.NpzFile#
- class numpy.lib.npyio.NpzFile(fid)[source]#
A dictionary-like object with lazy-loading of files in the zipped archive provided on construction.
NpzFileis used to load files in the NumPy.npzdata archive format. Files containing arrays in.npyformat are loaded as arrays; other files are returned as bytes.The arrays and bytes are lazily loaded on either getitem access using
obj['key']or attribute lookup usingobj.f.key. Full file names, including the.npysuffix, can also be used for getitem access and membership tests. A list of all file names, with the.npysuffix removed where present, can be obtained withobj.filesand the ZipFile object itself usingobj.zip.- Parameters:
- fidfile, str, or pathlib.Path
The zipped archive to open. This is either a file-like object or a string containing the path to the archive.
- own_fidbool, optional
Whether NpzFile should close the file handle. Requires that
fidis a file-like object.
- Attributes:
- fileslist of str
List of all file names in the archive, with the
.npysuffix removed where present.- zipZipFile instance
The ZipFile object initialized with the zipped archive.
- fBagObj instance
An object on which attribute can be performed as an alternative to getitem access on the
NpzFileinstance itself.- allow_picklebool, optional
Allow loading pickled data. Default: False
- pickle_kwargsdict, optional
Additional keyword arguments to pass on to pickle.load. These are only useful when loading object arrays saved on Python 2.
- max_header_sizeint, optional
Maximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See
ast.literal_evalfor details. This option is ignored when allow_pickle is passed. In that case the file is by definition trusted and the limit is unnecessary.
Methods
close()Close the file.
get(key[, default])D.get(k,[,d]) returns D[k] if k in D, else d.
items()D.items() returns a set-like object providing a view on the items
keys()D.keys() returns a set-like object providing a view on the keys
values()D.values() returns a set-like object providing a view on the values
Examples
>>> import numpy as np >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> y = np.sin(x) >>> np.savez(outfile, x=x, y=y) >>> _ = outfile.seek(0)
>>> npz = np.load(outfile) >>> isinstance(npz, np.lib.npyio.NpzFile) True >>> npz NpzFile 'object' with keys: x, y >>> sorted(npz.files) ['x', 'y'] >>> npz['x'] # getitem access array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> npz['x.npy'] # full file name array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> 'x.npy' in npz True >>> npz.f.x # attribute lookup array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])