Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
_npyio_impl.py2584 linesDownload Raw Back to lib
1"""
2IO related functions.
3"""
4import contextlib
5import functools
6import itertools
7import operator
8import os
9import pickle
10import re
11import warnings
12import weakref
13from collections.abc import Mapping
14from operator import itemgetter
15
16import numpy as np
17from numpy._core import overrides
18from numpy._core._multiarray_umath import _load_from_filelike
19from numpy._core.multiarray import packbits, unpackbits
20from numpy._core.overrides import finalize_array_function_like, set_module
21from numpy._utils import asbytes, asunicode
22
23from . import format
24from ._datasource import DataSource  # noqa: F401
25from ._format_impl import _MAX_HEADER_SIZE
26from ._iotools import (
27    ConversionWarning,
28    ConverterError,
29    ConverterLockError,
30    LineSplitter,
31    NameValidator,
32    StringConverter,
33    _decode_line,
34    _is_string_like,
35    easy_dtype,
36    flatten_dtype,
37    has_nested_fields,
38)
39
40__all__ = [
41    'savetxt', 'loadtxt', 'genfromtxt', 'load', 'save', 'savez',
42    'savez_compressed', 'packbits', 'unpackbits', 'fromregex'
43    ]
44
45
46array_function_dispatch = functools.partial(
47    overrides.array_function_dispatch, module='numpy')
48
49
50class BagObj:
51    """
52    BagObj(obj)
53
54    Convert attribute look-ups to getitems on the object passed in.
55
56    Parameters
57    ----------
58    obj : class instance
59        Object on which attribute look-up is performed.
60
61    Examples
62    --------
63    >>> import numpy as np
64    >>> from numpy.lib._npyio_impl import BagObj as BO
65    >>> class BagDemo:
66    ...     def __getitem__(self, key): # An instance of BagObj(BagDemo)
67    ...                                 # will call this method when any
68    ...                                 # attribute look-up is required
69    ...         result = "Doesn't matter what you want, "
70    ...         return result + "you're gonna get this"
71    ...
72    >>> demo_obj = BagDemo()
73    >>> bagobj = BO(demo_obj)
74    >>> bagobj.hello_there
75    "Doesn't matter what you want, you're gonna get this"
76    >>> bagobj.I_can_be_anything
77    "Doesn't matter what you want, you're gonna get this"
78
79    """
80
81    def __init__(self, obj):
82        # Use weakref to make NpzFile objects collectable by refcount
83        self._obj = weakref.proxy(obj)
84
85    def __getattribute__(self, key):
86        try:
87            return object.__getattribute__(self, '_obj')[key]
88        except KeyError:
89            raise AttributeError(key) from None
90
91    def __dir__(self):
92        """
93        Enables dir(bagobj) to list the files in an NpzFile.
94
95        This also enables tab-completion in an interpreter or IPython.
96        """
97        return list(object.__getattribute__(self, '_obj').keys())
98
99
100def zipfile_factory(file, *args, **kwargs):
101    """
102    Create a ZipFile.
103
104    Allows for Zip64, and the `file` argument can accept file, str, or
105    pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile
106    constructor.
107    """
108    if not hasattr(file, 'read'):
109        file = os.fspath(file)
110    import zipfile
111    kwargs['allowZip64'] = True
112    return zipfile.ZipFile(file, *args, **kwargs)
113
114
115@set_module('numpy.lib.npyio')
116class NpzFile(Mapping):
117    """
118    NpzFile(fid)
119
120    A dictionary-like object with lazy-loading of files in the zipped
121    archive provided on construction.
122
123    `NpzFile` is used to load files in the NumPy ``.npz`` data archive
124    format. It assumes that files in the archive have a ``.npy`` extension,
125    other files are ignored.
126
127    The arrays and file strings are lazily loaded on either
128    getitem access using ``obj['key']`` or attribute lookup using
129    ``obj.f.key``. A list of all files (without ``.npy`` extensions) can
130    be obtained with ``obj.files`` and the ZipFile object itself using
131    ``obj.zip``.
132
133    Attributes
134    ----------
135    files : list of str
136        List of all files in the archive with a ``.npy`` extension.
137    zip : ZipFile instance
138        The ZipFile object initialized with the zipped archive.
139    f : BagObj instance
140        An object on which attribute can be performed as an alternative
141        to getitem access on the `NpzFile` instance itself.
142    allow_pickle : bool, optional
143        Allow loading pickled data. Default: False
144    pickle_kwargs : dict, optional
145        Additional keyword arguments to pass on to pickle.load.
146        These are only useful when loading object arrays saved on
147        Python 2.
148    max_header_size : int, optional
149        Maximum allowed size of the header.  Large headers may not be safe
150        to load securely and thus require explicitly passing a larger value.
151        See :py:func:`ast.literal_eval()` for details.
152        This option is ignored when `allow_pickle` is passed.  In that case
153        the file is by definition trusted and the limit is unnecessary.
154
155    Parameters
156    ----------
157    fid : file, str, or pathlib.Path
158        The zipped archive to open. This is either a file-like object
159        or a string containing the path to the archive.
160    own_fid : bool, optional
161        Whether NpzFile should close the file handle.
162        Requires that `fid` is a file-like object.
163
164    Examples
165    --------
166    >>> import numpy as np
167    >>> from tempfile import TemporaryFile
168    >>> outfile = TemporaryFile()
169    >>> x = np.arange(10)
170    >>> y = np.sin(x)
171    >>> np.savez(outfile, x=x, y=y)
172    >>> _ = outfile.seek(0)
173
174    >>> npz = np.load(outfile)
175    >>> isinstance(npz, np.lib.npyio.NpzFile)
176    True
177    >>> npz
178    NpzFile 'object' with keys: x, y
179    >>> sorted(npz.files)
180    ['x', 'y']
181    >>> npz['x']  # getitem access
182    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
183    >>> npz.f.x  # attribute lookup
184    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
185
186    """
187    # Make __exit__ safe if zipfile_factory raises an exception
188    zip = None
189    fid = None
190    _MAX_REPR_ARRAY_COUNT = 5
191
192    def __init__(self, fid, own_fid=False, allow_pickle=False,
193                 pickle_kwargs=None, *,
194                 max_header_size=_MAX_HEADER_SIZE):
195        # Import is postponed to here since zipfile depends on gzip, an
196        # optional component of the so-called standard library.
197        _zip = zipfile_factory(fid)
198        _files = _zip.namelist()
199        self.files = [name.removesuffix(".npy") for name in _files]
200        self._files = dict(zip(self.files, _files))
201        self._files.update(zip(_files, _files))
202        self.allow_pickle = allow_pickle
203        self.max_header_size = max_header_size
204        self.pickle_kwargs = pickle_kwargs
205        self.zip = _zip
206        self.f = BagObj(self)
207        if own_fid:
208            self.fid = fid
209
210    def __enter__(self):
211        return self
212
213    def __exit__(self, exc_type, exc_value, traceback):
214        self.close()
215
216    def close(self):
217        """
218        Close the file.
219
220        """
221        if self.zip is not None:
222            self.zip.close()
223            self.zip = None
224        if self.fid is not None:
225            self.fid.close()
226            self.fid = None
227        self.f = None  # break reference cycle
228
229    def __del__(self):
230        self.close()
231
232    # Implement the Mapping ABC
233    def __iter__(self):
234        return iter(self.files)
235
236    def __len__(self):
237        return len(self.files)
238
239    def __getitem__(self, key):
240        try:
241            key = self._files[key]
242        except KeyError:
243            raise KeyError(f"{key} is not a file in the archive") from None
244        else:
245            with self.zip.open(key) as bytes:
246                magic = bytes.read(len(format.MAGIC_PREFIX))
247                bytes.seek(0)
248                if magic == format.MAGIC_PREFIX:
249                    # FIXME: This seems like it will copy strings around
250                    #   more than is strictly necessary.  The zipfile
251                    #   will read the string and then
252                    #   the format.read_array will copy the string
253                    #   to another place in memory.
254                    #   It would be better if the zipfile could read
255                    #   (or at least uncompress) the data
256                    #   directly into the array memory.
257                    return format.read_array(
258                        bytes,
259                        allow_pickle=self.allow_pickle,
260                        pickle_kwargs=self.pickle_kwargs,
261                        max_header_size=self.max_header_size
262                    )
263                else:
264                    return bytes.read()
265
266    def __contains__(self, key):
267        return (key in self._files)
268
269    def __repr__(self):
270        # Get filename or default to `object`
271        if isinstance(self.fid, str):
272            filename = self.fid
273        else:
274            filename = getattr(self.fid, "name", "object")
275
276        # Get the name of arrays
277        array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT])
278        if len(self.files) > self._MAX_REPR_ARRAY_COUNT:
279            array_names += "..."
280        return f"NpzFile {filename!r} with keys: {array_names}"
281
282    # Work around problems with the docstrings in the Mapping methods
283    # They contain a `->`, which confuses the type annotation interpretations
284    # of sphinx-docs. See gh-25964
285
286    def get(self, key, default=None, /):
287        """
288        D.get(k,[,d]) returns D[k] if k in D, else d.  d defaults to None.
289        """
290        return Mapping.get(self, key, default)
291
292    def items(self):
293        """
294        D.items() returns a set-like object providing a view on the items
295        """
296        return Mapping.items(self)
297
298    def keys(self):
299        """
300        D.keys() returns a set-like object providing a view on the keys
301        """
302        return Mapping.keys(self)
303
304    def values(self):
305        """
306        D.values() returns a set-like object providing a view on the values
307        """
308        return Mapping.values(self)
309
310
311@set_module('numpy')
312def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True,
313         encoding='ASCII', *, max_header_size=_MAX_HEADER_SIZE):
314    """
315    Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.
316
317    .. warning:: Loading files that contain object arrays uses the ``pickle``
318                 module, which is not secure against erroneous or maliciously
319                 constructed data. Consider passing ``allow_pickle=False`` to
320                 load data that is known not to contain object arrays for the
321                 safer handling of untrusted sources.
322
323    Parameters
324    ----------
325    file : file-like object, string, or pathlib.Path
326        The file to read. File-like objects must support the
327        ``seek()`` and ``read()`` methods and must always
328        be opened in binary mode.  Pickled files require that the
329        file-like object support the ``readline()`` method as well.
330    mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
331        If not None, then memory-map the file, using the given mode (see
332        `numpy.memmap` for a detailed description of the modes).  A
333        memory-mapped array is kept on disk. However, it can be accessed
334        and sliced like any ndarray.  Memory mapping is especially useful
335        for accessing small fragments of large files without reading the
336        entire file into memory.
337    allow_pickle : bool, optional
338        Allow loading pickled object arrays stored in npy files. Reasons for
339        disallowing pickles include security, as loading pickled data can
340        execute arbitrary code. If pickles are disallowed, loading object
341        arrays will fail. Default: False
342    fix_imports : bool, optional
343        Only useful when loading Python 2 generated pickled files,
344        which includes npy/npz files containing object arrays. If `fix_imports`
345        is True, pickle will try to map the old Python 2 names to the new names
346        used in Python 3.
347    encoding : str, optional
348        What encoding to use when reading Python 2 strings. Only useful when
349        loading Python 2 generated pickled files, which includes
350        npy/npz files containing object arrays. Values other than 'latin1',
351        'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
352        data. Default: 'ASCII'
353    max_header_size : int, optional
354        Maximum allowed size of the header.  Large headers may not be safe
355        to load securely and thus require explicitly passing a larger value.
356        See :py:func:`ast.literal_eval()` for details.
357        This option is ignored when `allow_pickle` is passed.  In that case
358        the file is by definition trusted and the limit is unnecessary.
359
360    Returns
361    -------
362    result : array, tuple, dict, etc.
363        Data stored in the file. For ``.npz`` files, the returned instance
364        of NpzFile class must be closed to avoid leaking file descriptors.
365
366    Raises
367    ------
368    OSError
369        If the input file does not exist or cannot be read.
370    UnpicklingError
371        If ``allow_pickle=True``, but the file cannot be loaded as a pickle.
372    ValueError
373        The file contains an object array, but ``allow_pickle=False`` given.
374    EOFError
375        When calling ``np.load`` multiple times on the same file handle,
376        if all data has already been read
377
378    See Also
379    --------
380    save, savez, savez_compressed, loadtxt
381    memmap : Create a memory-map to an array stored in a file on disk.
382    lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
383
384    Notes
385    -----
386    - If the file contains pickle data, then whatever object is stored
387      in the pickle is returned.
388    - If the file is a ``.npy`` file, then a single array is returned.
389    - If the file is a ``.npz`` file, then a dictionary-like object is
390      returned, containing ``{filename: array}`` key-value pairs, one for
391      each file in the archive.
392    - If the file is a ``.npz`` file, the returned value supports the
393      context manager protocol in a similar fashion to the open function::
394
395        with load('foo.npz') as data:
396            a = data['a']
397
398      The underlying file descriptor is closed when exiting the 'with'
399      block.
400
401    Examples
402    --------
403    >>> import numpy as np
404
405    Store data to disk, and load it again:
406
407    >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
408    >>> np.load('/tmp/123.npy')
409    array([[1, 2, 3],
410           [4, 5, 6]])
411
412    Store compressed data to disk, and load it again:
413
414    >>> a=np.array([[1, 2, 3], [4, 5, 6]])
415    >>> b=np.array([1, 2])
416    >>> np.savez('/tmp/123.npz', a=a, b=b)
417    >>> data = np.load('/tmp/123.npz')
418    >>> data['a']
419    array([[1, 2, 3],
420           [4, 5, 6]])
421    >>> data['b']
422    array([1, 2])
423    >>> data.close()
424
425    Mem-map the stored array, and then access the second row
426    directly from disk:
427
428    >>> X = np.load('/tmp/123.npy', mmap_mode='r')
429    >>> X[1, :]
430    memmap([4, 5, 6])
431
432    """
433    if encoding not in ('ASCII', 'latin1', 'bytes'):
434        # The 'encoding' value for pickle also affects what encoding
435        # the serialized binary data of NumPy arrays is loaded
436        # in. Pickle does not pass on the encoding information to
437        # NumPy. The unpickling code in numpy._core.multiarray is
438        # written to assume that unicode data appearing where binary
439        # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'.
440        #
441        # Other encoding values can corrupt binary data, and we
442        # purposefully disallow them. For the same reason, the errors=
443        # argument is not exposed, as values other than 'strict'
444        # result can similarly silently corrupt numerical data.
445        raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'")
446
447    pickle_kwargs = {'encoding': encoding, 'fix_imports': fix_imports}
448
449    with contextlib.ExitStack() as stack:
450        if hasattr(file, 'read'):
451            fid = file
452            own_fid = False
453        else:
454            fid = stack.enter_context(open(os.fspath(file), "rb"))
455            own_fid = True
456
457        # Code to distinguish from NumPy binary files and pickles.
458        _ZIP_PREFIX = b'PK\x03\x04'
459        _ZIP_SUFFIX = b'PK\x05\x06'  # empty zip files start with this
460        N = len(format.MAGIC_PREFIX)
461        magic = fid.read(N)
462        if not magic:
463            raise EOFError("No data left in file")
464        # If the file size is less than N, we need to make sure not
465        # to seek past the beginning of the file
466        fid.seek(-min(N, len(magic)), 1)  # back-up
467        if magic.startswith((_ZIP_PREFIX, _ZIP_SUFFIX)):
468            # zip-file (assume .npz)
469            # Potentially transfer file ownership to NpzFile
470            stack.pop_all()
471            ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle,
472                          pickle_kwargs=pickle_kwargs,
473                          max_header_size=max_header_size)
474            return ret
475        elif magic == format.MAGIC_PREFIX:
476            # .npy file
477            if mmap_mode:
478                if allow_pickle:
479                    max_header_size = 2**64
480                return format.open_memmap(file, mode=mmap_mode,
481                                          max_header_size=max_header_size)
482            else:
483                return format.read_array(fid, allow_pickle=allow_pickle,
484                                         pickle_kwargs=pickle_kwargs,
485                                         max_header_size=max_header_size)
486        else:
487            # Try a pickle
488            if not allow_pickle:
489                raise ValueError(
490                    "This file contains pickled (object) data. If you trust "
491                    "the file you can load it unsafely using the "
492                    "`allow_pickle=` keyword argument or `pickle.load()`.")
493            try:
494                return pickle.load(fid, **pickle_kwargs)
495            except Exception as e:
496                raise pickle.UnpicklingError(
497                    f"Failed to interpret file {file!r} as a pickle") from e
498
499
500def _save_dispatcher(file, arr, allow_pickle=None):
501    return (arr,)
502
503
504@array_function_dispatch(_save_dispatcher)
505def save(file, arr, allow_pickle=True):
506    """
507    Save an array to a binary file in NumPy ``.npy`` format.
508
509    Parameters
510    ----------
511    file : file, str, or pathlib.Path
512        File or filename to which the data is saved. If file is a file-object,
513        then the filename is unchanged.  If file is a string or Path,
514        a ``.npy`` extension will be appended to the filename if it does not
515        already have one.
516    arr : array_like
517        Array data to be saved.
518    allow_pickle : bool, optional
519        Allow saving object arrays using Python pickles. Reasons for
520        disallowing pickles include security (loading pickled data can execute
521        arbitrary code) and portability (pickled objects may not be loadable
522        on different Python installations, for example if the stored objects
523        require libraries that are not available, and not all pickled data is
524        compatible between different versions of Python).
525        Default: True
526
527    See Also
528    --------
529    savez : Save several arrays into a ``.npz`` archive
530    savetxt, load
531
532    Notes
533    -----
534    For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
535
536    Any data saved to the file is appended to the end of the file.
537
538    Examples
539    --------
540    >>> import numpy as np
541
542    >>> from tempfile import TemporaryFile
543    >>> outfile = TemporaryFile()
544
545    >>> x = np.arange(10)
546    >>> np.save(outfile, x)
547
548    >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
549    >>> np.load(outfile)
550    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
551
552
553    >>> with open('test.npy', 'wb') as f:
554    ...     np.save(f, np.array([1, 2]))
555    ...     np.save(f, np.array([1, 3]))
556    >>> with open('test.npy', 'rb') as f:
557    ...     a = np.load(f)
558    ...     b = np.load(f)
559    >>> print(a, b)
560    # [1 2] [1 3]
561    """
562    if hasattr(file, 'write'):
563        file_ctx = contextlib.nullcontext(file)
564    else:
565        file = os.fspath(file)
566        if not file.endswith('.npy'):
567            file = file + '.npy'
568        file_ctx = open(file, "wb")
569
570    with file_ctx as fid:
571        arr = np.asanyarray(arr)
572        format.write_array(fid, arr, allow_pickle=allow_pickle)
573
574
575def _savez_dispatcher(file, *args, allow_pickle=True, **kwds):
576    yield from args
577    yield from kwds.values()
578
579
580@array_function_dispatch(_savez_dispatcher)
581def savez(file, *args, allow_pickle=True, **kwds):
582    """Save several arrays into a single file in uncompressed ``.npz`` format.
583
584    Provide arrays as keyword arguments to store them under the
585    corresponding name in the output file: ``savez(fn, x=x, y=y)``.
586
587    If arrays are specified as positional arguments, i.e., ``savez(fn,
588    x, y)``, their names will be `arr_0`, `arr_1`, etc.
589
590    Parameters
591    ----------
592    file : file, str, or pathlib.Path
593        Either the filename (string) or an open file (file-like object)
594        where the data will be saved. If file is a string or a Path, the
595        ``.npz`` extension will be appended to the filename if it is not
596        already there.
597    args : Arguments, optional
598        Arrays to save to the file. Please use keyword arguments (see
599        `kwds` below) to assign names to arrays.  Arrays specified as
600        args will be named "arr_0", "arr_1", and so on.
601    allow_pickle : bool, optional
602        Allow saving object arrays using Python pickles. Reasons for
603        disallowing pickles include security (loading pickled data can execute
604        arbitrary code) and portability (pickled objects may not be loadable
605        on different Python installations, for example if the stored objects
606        require libraries that are not available, and not all pickled data is
607        compatible between different versions of Python).
608        Default: True
609    kwds : Keyword arguments, optional
610        Arrays to save to the file. Each array will be saved to the
611        output file with its corresponding keyword name.
612
613    Returns
614    -------
615    None
616
617    See Also
618    --------
619    save : Save a single array to a binary file in NumPy format.
620    savetxt : Save an array to a file as plain text.
621    savez_compressed : Save several arrays into a compressed ``.npz`` archive
622
623    Notes
624    -----
625    The ``.npz`` file format is a zipped archive of files named after the
626    variables they contain.  The archive is not compressed and each file
627    in the archive contains one variable in ``.npy`` format. For a
628    description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
629
630    When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
631    object is returned. This is a dictionary-like object which can be queried
632    for its list of arrays (with the ``.files`` attribute), and for the arrays
633    themselves.
634
635    Keys passed in `kwds` are used as filenames inside the ZIP archive.
636    Therefore, keys should be valid filenames; e.g., avoid keys that begin with
637    ``/`` or contain ``.``.
638
639    When naming variables with keyword arguments, it is not possible to name a
640    variable ``file``, as this would cause the ``file`` argument to be defined
641    twice in the call to ``savez``.
642
643    Examples
644    --------
645    >>> import numpy as np
646    >>> from tempfile import TemporaryFile
647    >>> outfile = TemporaryFile()
648    >>> x = np.arange(10)
649    >>> y = np.sin(x)
650
651    Using `savez` with \\*args, the arrays are saved with default names.
652
653    >>> np.savez(outfile, x, y)
654    >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
655    >>> npzfile = np.load(outfile)
656    >>> npzfile.files
657    ['arr_0', 'arr_1']
658    >>> npzfile['arr_0']
659    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
660
661    Using `savez` with \\**kwds, the arrays are saved with the keyword names.
662
663    >>> outfile = TemporaryFile()
664    >>> np.savez(outfile, x=x, y=y)
665    >>> _ = outfile.seek(0)
666    >>> npzfile = np.load(outfile)
667    >>> sorted(npzfile.files)
668    ['x', 'y']
669    >>> npzfile['x']
670    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
671
672    """
673    _savez(file, args, kwds, False, allow_pickle=allow_pickle)
674
675
676def _savez_compressed_dispatcher(file, *args, allow_pickle=True, **kwds):
677    yield from args
678    yield from kwds.values()
679
680
681@array_function_dispatch(_savez_compressed_dispatcher)
682def savez_compressed(file, *args, allow_pickle=True, **kwds):
683    """
684    Save several arrays into a single file in compressed ``.npz`` format.
685
686    Provide arrays as keyword arguments to store them under the
687    corresponding name in the output file: ``savez_compressed(fn, x=x, y=y)``.
688
689    If arrays are specified as positional arguments, i.e.,
690    ``savez_compressed(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc.
691
692    Parameters
693    ----------
694    file : file, str, or pathlib.Path
695        Either the filename (string) or an open file (file-like object)
696        where the data will be saved. If file is a string or a Path, the
697        ``.npz`` extension will be appended to the filename if it is not
698        already there.
699    args : Arguments, optional
700        Arrays to save to the file. Please use keyword arguments (see
701        `kwds` below) to assign names to arrays.  Arrays specified as
702        args will be named "arr_0", "arr_1", and so on.
703    allow_pickle : bool, optional
704        Allow saving object arrays using Python pickles. Reasons for
705        disallowing pickles include security (loading pickled data can execute
706        arbitrary code) and portability (pickled objects may not be loadable
707        on different Python installations, for example if the stored objects
708        require libraries that are not available, and not all pickled data is
709        compatible between different versions of Python).
710        Default: True
711    kwds : Keyword arguments, optional
712        Arrays to save to the file. Each array will be saved to the
713        output file with its corresponding keyword name.
714
715    Returns
716    -------
717    None
718
719    See Also
720    --------
721    numpy.save : Save a single array to a binary file in NumPy format.
722    numpy.savetxt : Save an array to a file as plain text.
723    numpy.savez : Save several arrays into an uncompressed ``.npz`` file format
724    numpy.load : Load the files created by savez_compressed.
725
726    Notes
727    -----
728    The ``.npz`` file format is a zipped archive of files named after the
729    variables they contain.  The archive is compressed with
730    ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable
731    in ``.npy`` format. For a description of the ``.npy`` format, see
732    :py:mod:`numpy.lib.format`.
733
734
735    When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
736    object is returned. This is a dictionary-like object which can be queried
737    for its list of arrays (with the ``.files`` attribute), and for the arrays
738    themselves.
739
740    Examples
741    --------
742    >>> import numpy as np
743    >>> test_array = np.random.rand(3, 2)
744    >>> test_vector = np.random.rand(4)
745    >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
746    >>> loaded = np.load('/tmp/123.npz')
747    >>> print(np.array_equal(test_array, loaded['a']))
748    True
749    >>> print(np.array_equal(test_vector, loaded['b']))
750    True
751
752    """
753    _savez(file, args, kwds, True, allow_pickle=allow_pickle)
754
755
756def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None):
757    # Import is postponed to here since zipfile depends on gzip, an optional
758    # component of the so-called standard library.
759    import zipfile
760
761    if not hasattr(file, 'write'):
762        file = os.fspath(file)
763        if not file.endswith('.npz'):
764            file = file + '.npz'
765
766    namedict = kwds
767    for i, val in enumerate(args):
768        key = 'arr_%d' % i
769        if key in namedict.keys():
770            raise ValueError(
771                f"Cannot use un-named variables and keyword {key}")
772        namedict[key] = val
773
774    if compress:
775        compression = zipfile.ZIP_DEFLATED
776    else:
777        compression = zipfile.ZIP_STORED
778
779    zipf = zipfile_factory(file, mode="w", compression=compression)
780    try:
781        for key, val in namedict.items():
782            fname = key + '.npy'
783            val = np.asanyarray(val)
784            # always force zip64, gh-10776
785            with zipf.open(fname, 'w', force_zip64=True) as fid:
786                format.write_array(fid, val,
787                                   allow_pickle=allow_pickle,
788                                   pickle_kwargs=pickle_kwargs)
789    finally:
790        zipf.close()
791
792
793def _ensure_ndmin_ndarray_check_param(ndmin):
794    """Just checks if the param ndmin is supported on
795        _ensure_ndmin_ndarray. It is intended to be used as
796        verification before running anything expensive.
797        e.g. loadtxt, genfromtxt
798    """
799    # Check correctness of the values of `ndmin`
800    if ndmin not in [0, 1, 2]:
801        raise ValueError(f"Illegal value of ndmin keyword: {ndmin}")
802
803def _ensure_ndmin_ndarray(a, *, ndmin: int):
804    """This is a helper function of loadtxt and genfromtxt to ensure
805        proper minimum dimension as requested
806
807        ndim : int. Supported values 1, 2, 3
808                    ^^ whenever this changes, keep in sync with
809                       _ensure_ndmin_ndarray_check_param
810    """
811    # Verify that the array has at least dimensions `ndmin`.
812    # Tweak the size and shape of the arrays - remove extraneous dimensions
813    if a.ndim > ndmin:
814        a = np.squeeze(a)
815    # and ensure we have the minimum number of dimensions asked for
816    # - has to be in this order for the odd case ndmin=1, a.squeeze().ndim=0
817    if a.ndim < ndmin:
818        if ndmin == 1:
819            a = np.atleast_1d(a)
820        elif ndmin == 2:
821            a = np.atleast_2d(a).T
822
823    return a
824
825
826# amount of lines loadtxt reads in one chunk, can be overridden for testing
827_loadtxt_chunksize = 50000
828
829
830def _check_nonneg_int(value, name="argument"):
831    try:
832        operator.index(value)
833    except TypeError:
834        raise TypeError(f"{name} must be an integer") from None
835    if value < 0:
836        raise ValueError(f"{name} must be nonnegative")
837
838
839def _preprocess_comments(iterable, comments, encoding):
840    """
841    Generator that consumes a line iterated iterable and strips out the
842    multiple (or multi-character) comments from lines.
843    This is a pre-processing step to achieve feature parity with loadtxt
844    (we assume that this feature is a nieche feature).
845    """
846    for line in iterable:
847        if isinstance(line, bytes):
848            # Need to handle conversion here, or the splitting would fail
849            line = line.decode(encoding)
850
851        for c in comments:
852            line = line.split(c, 1)[0]
853
854        yield line
855
856
857# The number of rows we read in one go if confronted with a parametric dtype
858_loadtxt_chunksize = 50000
859
860
861def _read(fname, *, delimiter=',', comment='#', quote='"',
862          imaginary_unit='j', usecols=None, skiplines=0,
863          max_rows=None, converters=None, ndmin=None, unpack=False,
864          dtype=np.float64, encoding=None):
865    r"""
866    Read a NumPy array from a text file.
867    This is a helper function for loadtxt.
868
869    Parameters
870    ----------
871    fname : file, str, or pathlib.Path
872        The filename or the file to be read.
873    delimiter : str, optional
874        Field delimiter of the fields in line of the file.
875        Default is a comma, ','.  If None any sequence of whitespace is
876        considered a delimiter.
877    comment : str or sequence of str or None, optional
878        Character that begins a comment.  All text from the comment
879        character to the end of the line is ignored.
880        Multiple comments or multiple-character comment strings are supported,
881        but may be slower and `quote` must be empty if used.
882        Use None to disable all use of comments.
883    quote : str or None, optional
884        Character that is used to quote string fields. Default is '"'
885        (a double quote). Use None to disable quote support.
886    imaginary_unit : str, optional
887        Character that represent the imaginary unit `sqrt(-1)`.
888        Default is 'j'.
889    usecols : array_like, optional
890        A one-dimensional array of integer column numbers.  These are the
891        columns from the file to be included in the array.  If this value
892        is not given, all the columns are used.
893    skiplines : int, optional
894        Number of lines to skip before interpreting the data in the file.
895    max_rows : int, optional
896        Maximum number of rows of data to read.  Default is to read the
897        entire file.
898    converters : dict or callable, optional
899        A function to parse all columns strings into the desired value, or
900        a dictionary mapping column number to a parser function.
901        E.g. if column 0 is a date string: ``converters = {0: datestr2num}``.
902        Converters can also be used to provide a default value for missing
903        data, e.g. ``converters = lambda s: float(s.strip() or 0)`` will
904        convert empty fields to 0.
905        Default: None
906    ndmin : int, optional
907        Minimum dimension of the array returned.
908        Allowed values are 0, 1 or 2.  Default is 0.
909    unpack : bool, optional
910        If True, the returned array is transposed, so that arguments may be
911        unpacked using ``x, y, z = read(...)``.  When used with a structured
912        data-type, arrays are returned for each field.  Default is False.
913    dtype : numpy data type
914        A NumPy dtype instance, can be a structured dtype to map to the
915        columns of the file.
916    encoding : str, optional
917        Encoding used to decode the inputfile. The special value 'bytes'
918        (the default) enables backwards-compatible behavior for `converters`,
919        ensuring that inputs to the converter functions are encoded
920        bytes objects. The special value 'bytes' has no additional effect if
921        ``converters=None``. If encoding is ``'bytes'`` or ``None``, the
922        default system encoding is used.
923
924    Returns
925    -------
926    ndarray
927        NumPy array.
928    """
929    # Handle special 'bytes' keyword for encoding
930    byte_converters = False
931    if encoding == 'bytes':
932        encoding = None
933        byte_converters = True
934
935    if dtype is None:
936        raise TypeError("a dtype must be provided.")
937    dtype = np.dtype(dtype)
938
939    read_dtype_via_object_chunks = None
940    if dtype.kind in 'SUM' and dtype in {
941            np.dtype("S0"), np.dtype("U0"), np.dtype("M8"), np.dtype("m8")}:
942        # This is a legacy "flexible" dtype.  We do not truly support
943        # parametric dtypes currently (no dtype discovery step in the core),
944        # but have to support these for backward compatibility.
945        read_dtype_via_object_chunks = dtype
946        dtype = np.dtype(object)
947
948    if usecols is not None:
949        # Allow usecols to be a single int or a sequence of ints, the C-code
950        # handles the rest
951        try:
952            usecols = list(usecols)
953        except TypeError:
954            usecols = [usecols]
955
956    _ensure_ndmin_ndarray_check_param(ndmin)
957
958    if comment is None:
959        comments = None
960    else:
961        # assume comments are a sequence of strings
962        if "" in comment:
963            raise ValueError(
964                "comments cannot be an empty string. Use comments=None to "
965                "disable comments."
966            )
967        comments = tuple(comment)
968        comment = None
969        if len(comments) == 0:
970            comments = None  # No comments at all
971        elif len(comments) == 1:
972            # If there is only one comment, and that comment has one character,
973            # the normal parsing can deal with it just fine.
974            if isinstance(comments[0], str) and len(comments[0]) == 1:
975                comment = comments[0]
976                comments = None
977        # Input validation if there are multiple comment characters
978        elif delimiter in comments:
979            raise TypeError(
980                f"Comment characters '{comments}' cannot include the "
981                f"delimiter '{delimiter}'"
982            )
983
984    # comment is now either a 1 or 0 character string or a tuple:
985    if comments is not None:
986        # Note: An earlier version support two character comments (and could
987        #       have been extended to multiple characters, we assume this is
988        #       rare enough to not optimize for.
989        if quote is not None:
990            raise ValueError(
991                "when multiple comments or a multi-character comment is "
992                "given, quotes are not supported.  In this case quotechar "
993                "must be set to None.")
994
995    if len(imaginary_unit) != 1:
996        raise ValueError('len(imaginary_unit) must be 1.')
997
998    _check_nonneg_int(skiplines)
999    if max_rows is not None:
1000        _check_nonneg_int(max_rows)
1001    else:
1002        # Passing -1 to the C code means "read the entire file".
1003        max_rows = -1
1004
1005    fh_closing_ctx = contextlib.nullcontext()
1006    filelike = False
1007    try:
1008        if isinstance(fname, os.PathLike):
1009            fname = os.fspath(fname)
1010        if isinstance(fname, str):
1011            fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
1012            if encoding is None:
1013                encoding = getattr(fh, 'encoding', 'latin1')
1014
1015            fh_closing_ctx = contextlib.closing(fh)
1016            data = fh
1017            filelike = True
1018        else:
1019            if encoding is None:
1020                encoding = getattr(fname, 'encoding', 'latin1')
1021            data = iter(fname)
1022    except TypeError as e:
1023        raise ValueError(
1024            f"fname must be a string, filehandle, list of strings,\n"
1025            f"or generator. Got {type(fname)} instead.") from e
1026
1027    with fh_closing_ctx:
1028        if comments is not None:
1029            if filelike:
1030                data = iter(data)
1031                filelike = False
1032            data = _preprocess_comments(data, comments, encoding)
1033
1034        if read_dtype_via_object_chunks is None:
1035            arr = _load_from_filelike(
1036                data, delimiter=delimiter, comment=comment, quote=quote,
1037                imaginary_unit=imaginary_unit,
1038                usecols=usecols, skiplines=skiplines, max_rows=max_rows,
1039                converters=converters, dtype=dtype,
1040                encoding=encoding, filelike=filelike,
1041                byte_converters=byte_converters)
1042
1043        else:
1044            # This branch reads the file into chunks of object arrays and then
1045            # casts them to the desired actual dtype.  This ensures correct
1046            # string-length and datetime-unit discovery (like `arr.astype()`).
1047            # Due to chunking, certain error reports are less clear, currently.
1048            if filelike:
1049                data = iter(data)  # cannot chunk when reading from file
1050                filelike = False
1051
1052            c_byte_converters = False
1053            if read_dtype_via_object_chunks == "S":
1054                c_byte_converters = True  # Use latin1 rather than ascii
1055
1056            chunks = []
1057            while max_rows != 0:
1058                if max_rows < 0:
1059                    chunk_size = _loadtxt_chunksize
1060                else:
1061                    chunk_size = min(_loadtxt_chunksize, max_rows)
1062
1063                next_arr = _load_from_filelike(
1064                    data, delimiter=delimiter, comment=comment, quote=quote,
1065                    imaginary_unit=imaginary_unit,
1066                    usecols=usecols, skiplines=skiplines, max_rows=chunk_size,
1067                    converters=converters, dtype=dtype,
1068                    encoding=encoding, filelike=filelike,
1069                    byte_converters=byte_converters,
1070                    c_byte_converters=c_byte_converters)
1071                # Cast here already.  We hope that this is better even for
1072                # large files because the storage is more compact.  It could
1073                # be adapted (in principle the concatenate could cast).
1074                chunks.append(next_arr.astype(read_dtype_via_object_chunks))
1075
1076                skiplines = 0  # Only have to skip for first chunk
1077                if max_rows >= 0:
1078                    max_rows -= chunk_size
1079                if len(next_arr) < chunk_size:
1080                    # There was less data than requested, so we are done.
1081                    break
1082
1083            # Need at least one chunk, but if empty, the last one may have
1084            # the wrong shape.
1085            if len(chunks) > 1 and len(chunks[-1]) == 0:
1086                del chunks[-1]
1087            if len(chunks) == 1:
1088                arr = chunks[0]
1089            else:
1090                arr = np.concatenate(chunks, axis=0)
1091
1092    # NOTE: ndmin works as advertised for structured dtypes, but normally
1093    #       these would return a 1D result plus the structured dimension,
1094    #       so ndmin=2 adds a third dimension even when no squeezing occurs.
1095    #       A `squeeze=False` could be a better solution (pandas uses squeeze).
1096    arr = _ensure_ndmin_ndarray(arr, ndmin=ndmin)
1097
1098    if arr.shape:
1099        if arr.shape[0] == 0:
1100            warnings.warn(
1101                f'loadtxt: input contained no data: "{fname}"',
1102                category=UserWarning,
1103                stacklevel=3
1104            )
1105
1106    if unpack:
1107        # Unpack structured dtypes if requested:
1108        dt = arr.dtype
1109        if dt.names is not None:
1110            # For structured arrays, return an array for each field.
1111            return [arr[field] for field in dt.names]
1112        else:
1113            return arr.T
1114    else:
1115        return arr
1116
1117
1118@finalize_array_function_like
1119@set_module('numpy')
1120def loadtxt(fname, dtype=float, comments='#', delimiter=None,
1121            converters=None, skiprows=0, usecols=None, unpack=False,
1122            ndmin=0, encoding=None, max_rows=None, *, quotechar=None,
1123            like=None):
1124    r"""
1125    Load data from a text file.
1126
1127    Parameters
1128    ----------
1129    fname : file, str, pathlib.Path, list of str, generator
1130        File, filename, list, or generator to read.  If the filename
1131        extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
1132        that generators must return bytes or strings. The strings
1133        in a list or produced by a generator are treated as lines.
1134    dtype : data-type, optional
1135        Data-type of the resulting array; default: float.  If this is a
1136        structured data-type, the resulting array will be 1-dimensional, and
1137        each row will be interpreted as an element of the array.  In this
1138        case, the number of columns used must match the number of fields in
1139        the data-type.
1140    comments : str or sequence of str or None, optional
1141        The characters or list of characters used to indicate the start of a
1142        comment. None implies no comments. For backwards compatibility, byte
1143        strings will be decoded as 'latin1'. The default is '#'.
1144    delimiter : str, optional
1145        The character used to separate the values. For backwards compatibility,
1146        byte strings will be decoded as 'latin1'. The default is whitespace.
1147
1148        .. versionchanged:: 1.23.0
1149           Only single character delimiters are supported. Newline characters
1150           cannot be used as the delimiter.
1151
1152    converters : dict or callable, optional
1153        Converter functions to customize value parsing. If `converters` is
1154        callable, the function is applied to all columns, else it must be a
1155        dict that maps column number to a parser function.
1156        See examples for further details.
1157        Default: None.
1158
1159        .. versionchanged:: 1.23.0
1160           The ability to pass a single callable to be applied to all columns
1161           was added.
1162
1163    skiprows : int, optional
1164        Skip the first `skiprows` lines, including comments; default: 0.
1165    usecols : int or sequence, optional
1166        Which columns to read, with 0 being the first. For example,
1167        ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
1168        The default, None, results in all columns being read.
1169    unpack : bool, optional
1170        If True, the returned array is transposed, so that arguments may be
1171        unpacked using ``x, y, z = loadtxt(...)``.  When used with a
1172        structured data-type, arrays are returned for each field.
1173        Default is False.
1174    ndmin : int, optional
1175        The returned array will have at least `ndmin` dimensions.
1176        Otherwise mono-dimensional axes will be squeezed.
1177        Legal values: 0 (default), 1 or 2.
1178    encoding : str, optional
1179        Encoding used to decode the inputfile. Does not apply to input streams.
1180        The special value 'bytes' enables backward compatibility workarounds
1181        that ensures you receive byte arrays as results if possible and passes
1182        'latin1' encoded strings to converters. Override this value to receive
1183        unicode arrays and pass strings as input to converters.  If set to None
1184        the system default is used. The default value is None.
1185
1186        .. versionchanged:: 2.0
1187            Before NumPy 2, the default was ``'bytes'`` for Python 2
1188            compatibility. The default is now ``None``.
1189
1190    max_rows : int, optional
1191        Read `max_rows` rows of content after `skiprows` lines. The default is
1192        to read all the rows. Note that empty rows containing no data such as
1193        empty lines and comment lines are not counted towards `max_rows`,
1194        while such lines are counted in `skiprows`.
1195
1196        .. versionchanged:: 1.23.0
1197            Lines containing no data, including comment lines (e.g., lines
1198            starting with '#' or as specified via `comments`) are not counted
1199            towards `max_rows`.
1200    quotechar : unicode character or None, optional

Showing the first 1,200 of 2584 lines. Download the file for the rest.