_npyio_impl.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583
  1. """
  2. IO related functions.
  3. """
  4. import contextlib
  5. import functools
  6. import itertools
  7. import operator
  8. import os
  9. import pickle
  10. import re
  11. import warnings
  12. import weakref
  13. from collections.abc import Mapping
  14. from operator import itemgetter
  15. import numpy as np
  16. from numpy._core import overrides
  17. from numpy._core._multiarray_umath import _load_from_filelike
  18. from numpy._core.multiarray import packbits, unpackbits
  19. from numpy._core.overrides import finalize_array_function_like, set_module
  20. from numpy._utils import asbytes, asunicode
  21. from . import format
  22. from ._datasource import DataSource # noqa: F401
  23. from ._format_impl import _MAX_HEADER_SIZE
  24. from ._iotools import (
  25. ConversionWarning,
  26. ConverterError,
  27. ConverterLockError,
  28. LineSplitter,
  29. NameValidator,
  30. StringConverter,
  31. _decode_line,
  32. _is_string_like,
  33. easy_dtype,
  34. flatten_dtype,
  35. has_nested_fields,
  36. )
  37. __all__ = [
  38. 'savetxt', 'loadtxt', 'genfromtxt', 'load', 'save', 'savez',
  39. 'savez_compressed', 'packbits', 'unpackbits', 'fromregex'
  40. ]
  41. array_function_dispatch = functools.partial(
  42. overrides.array_function_dispatch, module='numpy')
  43. class BagObj:
  44. """
  45. BagObj(obj)
  46. Convert attribute look-ups to getitems on the object passed in.
  47. Parameters
  48. ----------
  49. obj : class instance
  50. Object on which attribute look-up is performed.
  51. Examples
  52. --------
  53. >>> import numpy as np
  54. >>> from numpy.lib._npyio_impl import BagObj as BO
  55. >>> class BagDemo:
  56. ... def __getitem__(self, key): # An instance of BagObj(BagDemo)
  57. ... # will call this method when any
  58. ... # attribute look-up is required
  59. ... result = "Doesn't matter what you want, "
  60. ... return result + "you're gonna get this"
  61. ...
  62. >>> demo_obj = BagDemo()
  63. >>> bagobj = BO(demo_obj)
  64. >>> bagobj.hello_there
  65. "Doesn't matter what you want, you're gonna get this"
  66. >>> bagobj.I_can_be_anything
  67. "Doesn't matter what you want, you're gonna get this"
  68. """
  69. def __init__(self, obj):
  70. # Use weakref to make NpzFile objects collectable by refcount
  71. self._obj = weakref.proxy(obj)
  72. def __getattribute__(self, key):
  73. try:
  74. return object.__getattribute__(self, '_obj')[key]
  75. except KeyError:
  76. raise AttributeError(key) from None
  77. def __dir__(self):
  78. """
  79. Enables dir(bagobj) to list the files in an NpzFile.
  80. This also enables tab-completion in an interpreter or IPython.
  81. """
  82. return list(object.__getattribute__(self, '_obj').keys())
  83. def zipfile_factory(file, *args, **kwargs):
  84. """
  85. Create a ZipFile.
  86. Allows for Zip64, and the `file` argument can accept file, str, or
  87. pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile
  88. constructor.
  89. """
  90. if not hasattr(file, 'read'):
  91. file = os.fspath(file)
  92. import zipfile
  93. kwargs['allowZip64'] = True
  94. return zipfile.ZipFile(file, *args, **kwargs)
  95. @set_module('numpy.lib.npyio')
  96. class NpzFile(Mapping):
  97. """
  98. NpzFile(fid)
  99. A dictionary-like object with lazy-loading of files in the zipped
  100. archive provided on construction.
  101. `NpzFile` is used to load files in the NumPy ``.npz`` data archive
  102. format. It assumes that files in the archive have a ``.npy`` extension,
  103. other files are ignored.
  104. The arrays and file strings are lazily loaded on either
  105. getitem access using ``obj['key']`` or attribute lookup using
  106. ``obj.f.key``. A list of all files (without ``.npy`` extensions) can
  107. be obtained with ``obj.files`` and the ZipFile object itself using
  108. ``obj.zip``.
  109. Attributes
  110. ----------
  111. files : list of str
  112. List of all files in the archive with a ``.npy`` extension.
  113. zip : ZipFile instance
  114. The ZipFile object initialized with the zipped archive.
  115. f : BagObj instance
  116. An object on which attribute can be performed as an alternative
  117. to getitem access on the `NpzFile` instance itself.
  118. allow_pickle : bool, optional
  119. Allow loading pickled data. Default: False
  120. pickle_kwargs : dict, optional
  121. Additional keyword arguments to pass on to pickle.load.
  122. These are only useful when loading object arrays saved on
  123. Python 2.
  124. max_header_size : int, optional
  125. Maximum allowed size of the header. Large headers may not be safe
  126. to load securely and thus require explicitly passing a larger value.
  127. See :py:func:`ast.literal_eval()` for details.
  128. This option is ignored when `allow_pickle` is passed. In that case
  129. the file is by definition trusted and the limit is unnecessary.
  130. Parameters
  131. ----------
  132. fid : file, str, or pathlib.Path
  133. The zipped archive to open. This is either a file-like object
  134. or a string containing the path to the archive.
  135. own_fid : bool, optional
  136. Whether NpzFile should close the file handle.
  137. Requires that `fid` is a file-like object.
  138. Examples
  139. --------
  140. >>> import numpy as np
  141. >>> from tempfile import TemporaryFile
  142. >>> outfile = TemporaryFile()
  143. >>> x = np.arange(10)
  144. >>> y = np.sin(x)
  145. >>> np.savez(outfile, x=x, y=y)
  146. >>> _ = outfile.seek(0)
  147. >>> npz = np.load(outfile)
  148. >>> isinstance(npz, np.lib.npyio.NpzFile)
  149. True
  150. >>> npz
  151. NpzFile 'object' with keys: x, y
  152. >>> sorted(npz.files)
  153. ['x', 'y']
  154. >>> npz['x'] # getitem access
  155. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  156. >>> npz.f.x # attribute lookup
  157. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  158. """
  159. # Make __exit__ safe if zipfile_factory raises an exception
  160. zip = None
  161. fid = None
  162. _MAX_REPR_ARRAY_COUNT = 5
  163. def __init__(self, fid, own_fid=False, allow_pickle=False,
  164. pickle_kwargs=None, *,
  165. max_header_size=_MAX_HEADER_SIZE):
  166. # Import is postponed to here since zipfile depends on gzip, an
  167. # optional component of the so-called standard library.
  168. _zip = zipfile_factory(fid)
  169. _files = _zip.namelist()
  170. self.files = [name.removesuffix(".npy") for name in _files]
  171. self._files = dict(zip(self.files, _files))
  172. self._files.update(zip(_files, _files))
  173. self.allow_pickle = allow_pickle
  174. self.max_header_size = max_header_size
  175. self.pickle_kwargs = pickle_kwargs
  176. self.zip = _zip
  177. self.f = BagObj(self)
  178. if own_fid:
  179. self.fid = fid
  180. def __enter__(self):
  181. return self
  182. def __exit__(self, exc_type, exc_value, traceback):
  183. self.close()
  184. def close(self):
  185. """
  186. Close the file.
  187. """
  188. if self.zip is not None:
  189. self.zip.close()
  190. self.zip = None
  191. if self.fid is not None:
  192. self.fid.close()
  193. self.fid = None
  194. self.f = None # break reference cycle
  195. def __del__(self):
  196. self.close()
  197. # Implement the Mapping ABC
  198. def __iter__(self):
  199. return iter(self.files)
  200. def __len__(self):
  201. return len(self.files)
  202. def __getitem__(self, key):
  203. try:
  204. key = self._files[key]
  205. except KeyError:
  206. raise KeyError(f"{key} is not a file in the archive") from None
  207. else:
  208. with self.zip.open(key) as bytes:
  209. magic = bytes.read(len(format.MAGIC_PREFIX))
  210. bytes.seek(0)
  211. if magic == format.MAGIC_PREFIX:
  212. # FIXME: This seems like it will copy strings around
  213. # more than is strictly necessary. The zipfile
  214. # will read the string and then
  215. # the format.read_array will copy the string
  216. # to another place in memory.
  217. # It would be better if the zipfile could read
  218. # (or at least uncompress) the data
  219. # directly into the array memory.
  220. return format.read_array(
  221. bytes,
  222. allow_pickle=self.allow_pickle,
  223. pickle_kwargs=self.pickle_kwargs,
  224. max_header_size=self.max_header_size
  225. )
  226. else:
  227. return bytes.read()
  228. def __contains__(self, key):
  229. return (key in self._files)
  230. def __repr__(self):
  231. # Get filename or default to `object`
  232. if isinstance(self.fid, str):
  233. filename = self.fid
  234. else:
  235. filename = getattr(self.fid, "name", "object")
  236. # Get the name of arrays
  237. array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT])
  238. if len(self.files) > self._MAX_REPR_ARRAY_COUNT:
  239. array_names += "..."
  240. return f"NpzFile {filename!r} with keys: {array_names}"
  241. # Work around problems with the docstrings in the Mapping methods
  242. # They contain a `->`, which confuses the type annotation interpretations
  243. # of sphinx-docs. See gh-25964
  244. def get(self, key, default=None, /):
  245. """
  246. D.get(k,[,d]) returns D[k] if k in D, else d. d defaults to None.
  247. """
  248. return Mapping.get(self, key, default)
  249. def items(self):
  250. """
  251. D.items() returns a set-like object providing a view on the items
  252. """
  253. return Mapping.items(self)
  254. def keys(self):
  255. """
  256. D.keys() returns a set-like object providing a view on the keys
  257. """
  258. return Mapping.keys(self)
  259. def values(self):
  260. """
  261. D.values() returns a set-like object providing a view on the values
  262. """
  263. return Mapping.values(self)
  264. @set_module('numpy')
  265. def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True,
  266. encoding='ASCII', *, max_header_size=_MAX_HEADER_SIZE):
  267. """
  268. Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.
  269. .. warning:: Loading files that contain object arrays uses the ``pickle``
  270. module, which is not secure against erroneous or maliciously
  271. constructed data. Consider passing ``allow_pickle=False`` to
  272. load data that is known not to contain object arrays for the
  273. safer handling of untrusted sources.
  274. Parameters
  275. ----------
  276. file : file-like object, string, or pathlib.Path
  277. The file to read. File-like objects must support the
  278. ``seek()`` and ``read()`` methods and must always
  279. be opened in binary mode. Pickled files require that the
  280. file-like object support the ``readline()`` method as well.
  281. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
  282. If not None, then memory-map the file, using the given mode (see
  283. `numpy.memmap` for a detailed description of the modes). A
  284. memory-mapped array is kept on disk. However, it can be accessed
  285. and sliced like any ndarray. Memory mapping is especially useful
  286. for accessing small fragments of large files without reading the
  287. entire file into memory.
  288. allow_pickle : bool, optional
  289. Allow loading pickled object arrays stored in npy files. Reasons for
  290. disallowing pickles include security, as loading pickled data can
  291. execute arbitrary code. If pickles are disallowed, loading object
  292. arrays will fail. Default: False
  293. fix_imports : bool, optional
  294. Only useful when loading Python 2 generated pickled files,
  295. which includes npy/npz files containing object arrays. If `fix_imports`
  296. is True, pickle will try to map the old Python 2 names to the new names
  297. used in Python 3.
  298. encoding : str, optional
  299. What encoding to use when reading Python 2 strings. Only useful when
  300. loading Python 2 generated pickled files, which includes
  301. npy/npz files containing object arrays. Values other than 'latin1',
  302. 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
  303. data. Default: 'ASCII'
  304. max_header_size : int, optional
  305. Maximum allowed size of the header. Large headers may not be safe
  306. to load securely and thus require explicitly passing a larger value.
  307. See :py:func:`ast.literal_eval()` for details.
  308. This option is ignored when `allow_pickle` is passed. In that case
  309. the file is by definition trusted and the limit is unnecessary.
  310. Returns
  311. -------
  312. result : array, tuple, dict, etc.
  313. Data stored in the file. For ``.npz`` files, the returned instance
  314. of NpzFile class must be closed to avoid leaking file descriptors.
  315. Raises
  316. ------
  317. OSError
  318. If the input file does not exist or cannot be read.
  319. UnpicklingError
  320. If ``allow_pickle=True``, but the file cannot be loaded as a pickle.
  321. ValueError
  322. The file contains an object array, but ``allow_pickle=False`` given.
  323. EOFError
  324. When calling ``np.load`` multiple times on the same file handle,
  325. if all data has already been read
  326. See Also
  327. --------
  328. save, savez, savez_compressed, loadtxt
  329. memmap : Create a memory-map to an array stored in a file on disk.
  330. lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
  331. Notes
  332. -----
  333. - If the file contains pickle data, then whatever object is stored
  334. in the pickle is returned.
  335. - If the file is a ``.npy`` file, then a single array is returned.
  336. - If the file is a ``.npz`` file, then a dictionary-like object is
  337. returned, containing ``{filename: array}`` key-value pairs, one for
  338. each file in the archive.
  339. - If the file is a ``.npz`` file, the returned value supports the
  340. context manager protocol in a similar fashion to the open function::
  341. with load('foo.npz') as data:
  342. a = data['a']
  343. The underlying file descriptor is closed when exiting the 'with'
  344. block.
  345. Examples
  346. --------
  347. >>> import numpy as np
  348. Store data to disk, and load it again:
  349. >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
  350. >>> np.load('/tmp/123.npy')
  351. array([[1, 2, 3],
  352. [4, 5, 6]])
  353. Store compressed data to disk, and load it again:
  354. >>> a=np.array([[1, 2, 3], [4, 5, 6]])
  355. >>> b=np.array([1, 2])
  356. >>> np.savez('/tmp/123.npz', a=a, b=b)
  357. >>> data = np.load('/tmp/123.npz')
  358. >>> data['a']
  359. array([[1, 2, 3],
  360. [4, 5, 6]])
  361. >>> data['b']
  362. array([1, 2])
  363. >>> data.close()
  364. Mem-map the stored array, and then access the second row
  365. directly from disk:
  366. >>> X = np.load('/tmp/123.npy', mmap_mode='r')
  367. >>> X[1, :]
  368. memmap([4, 5, 6])
  369. """
  370. if encoding not in ('ASCII', 'latin1', 'bytes'):
  371. # The 'encoding' value for pickle also affects what encoding
  372. # the serialized binary data of NumPy arrays is loaded
  373. # in. Pickle does not pass on the encoding information to
  374. # NumPy. The unpickling code in numpy._core.multiarray is
  375. # written to assume that unicode data appearing where binary
  376. # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'.
  377. #
  378. # Other encoding values can corrupt binary data, and we
  379. # purposefully disallow them. For the same reason, the errors=
  380. # argument is not exposed, as values other than 'strict'
  381. # result can similarly silently corrupt numerical data.
  382. raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'")
  383. pickle_kwargs = {'encoding': encoding, 'fix_imports': fix_imports}
  384. with contextlib.ExitStack() as stack:
  385. if hasattr(file, 'read'):
  386. fid = file
  387. own_fid = False
  388. else:
  389. fid = stack.enter_context(open(os.fspath(file), "rb"))
  390. own_fid = True
  391. # Code to distinguish from NumPy binary files and pickles.
  392. _ZIP_PREFIX = b'PK\x03\x04'
  393. _ZIP_SUFFIX = b'PK\x05\x06' # empty zip files start with this
  394. N = len(format.MAGIC_PREFIX)
  395. magic = fid.read(N)
  396. if not magic:
  397. raise EOFError("No data left in file")
  398. # If the file size is less than N, we need to make sure not
  399. # to seek past the beginning of the file
  400. fid.seek(-min(N, len(magic)), 1) # back-up
  401. if magic.startswith((_ZIP_PREFIX, _ZIP_SUFFIX)):
  402. # zip-file (assume .npz)
  403. # Potentially transfer file ownership to NpzFile
  404. stack.pop_all()
  405. ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle,
  406. pickle_kwargs=pickle_kwargs,
  407. max_header_size=max_header_size)
  408. return ret
  409. elif magic == format.MAGIC_PREFIX:
  410. # .npy file
  411. if mmap_mode:
  412. if allow_pickle:
  413. max_header_size = 2**64
  414. return format.open_memmap(file, mode=mmap_mode,
  415. max_header_size=max_header_size)
  416. else:
  417. return format.read_array(fid, allow_pickle=allow_pickle,
  418. pickle_kwargs=pickle_kwargs,
  419. max_header_size=max_header_size)
  420. else:
  421. # Try a pickle
  422. if not allow_pickle:
  423. raise ValueError(
  424. "This file contains pickled (object) data. If you trust "
  425. "the file you can load it unsafely using the "
  426. "`allow_pickle=` keyword argument or `pickle.load()`.")
  427. try:
  428. return pickle.load(fid, **pickle_kwargs)
  429. except Exception as e:
  430. raise pickle.UnpicklingError(
  431. f"Failed to interpret file {file!r} as a pickle") from e
  432. def _save_dispatcher(file, arr, allow_pickle=None):
  433. return (arr,)
  434. @array_function_dispatch(_save_dispatcher)
  435. def save(file, arr, allow_pickle=True):
  436. """
  437. Save an array to a binary file in NumPy ``.npy`` format.
  438. Parameters
  439. ----------
  440. file : file, str, or pathlib.Path
  441. File or filename to which the data is saved. If file is a file-object,
  442. then the filename is unchanged. If file is a string or Path,
  443. a ``.npy`` extension will be appended to the filename if it does not
  444. already have one.
  445. arr : array_like
  446. Array data to be saved.
  447. allow_pickle : bool, optional
  448. Allow saving object arrays using Python pickles. Reasons for
  449. disallowing pickles include security (loading pickled data can execute
  450. arbitrary code) and portability (pickled objects may not be loadable
  451. on different Python installations, for example if the stored objects
  452. require libraries that are not available, and not all pickled data is
  453. compatible between different versions of Python).
  454. Default: True
  455. See Also
  456. --------
  457. savez : Save several arrays into a ``.npz`` archive
  458. savetxt, load
  459. Notes
  460. -----
  461. For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
  462. Any data saved to the file is appended to the end of the file.
  463. Examples
  464. --------
  465. >>> import numpy as np
  466. >>> from tempfile import TemporaryFile
  467. >>> outfile = TemporaryFile()
  468. >>> x = np.arange(10)
  469. >>> np.save(outfile, x)
  470. >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
  471. >>> np.load(outfile)
  472. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  473. >>> with open('test.npy', 'wb') as f:
  474. ... np.save(f, np.array([1, 2]))
  475. ... np.save(f, np.array([1, 3]))
  476. >>> with open('test.npy', 'rb') as f:
  477. ... a = np.load(f)
  478. ... b = np.load(f)
  479. >>> print(a, b)
  480. # [1 2] [1 3]
  481. """
  482. if hasattr(file, 'write'):
  483. file_ctx = contextlib.nullcontext(file)
  484. else:
  485. file = os.fspath(file)
  486. if not file.endswith('.npy'):
  487. file = file + '.npy'
  488. file_ctx = open(file, "wb")
  489. with file_ctx as fid:
  490. arr = np.asanyarray(arr)
  491. format.write_array(fid, arr, allow_pickle=allow_pickle)
  492. def _savez_dispatcher(file, *args, allow_pickle=True, **kwds):
  493. yield from args
  494. yield from kwds.values()
  495. @array_function_dispatch(_savez_dispatcher)
  496. def savez(file, *args, allow_pickle=True, **kwds):
  497. """Save several arrays into a single file in uncompressed ``.npz`` format.
  498. Provide arrays as keyword arguments to store them under the
  499. corresponding name in the output file: ``savez(fn, x=x, y=y)``.
  500. If arrays are specified as positional arguments, i.e., ``savez(fn,
  501. x, y)``, their names will be `arr_0`, `arr_1`, etc.
  502. Parameters
  503. ----------
  504. file : file, str, or pathlib.Path
  505. Either the filename (string) or an open file (file-like object)
  506. where the data will be saved. If file is a string or a Path, the
  507. ``.npz`` extension will be appended to the filename if it is not
  508. already there.
  509. args : Arguments, optional
  510. Arrays to save to the file. Please use keyword arguments (see
  511. `kwds` below) to assign names to arrays. Arrays specified as
  512. args will be named "arr_0", "arr_1", and so on.
  513. allow_pickle : bool, optional
  514. Allow saving object arrays using Python pickles. Reasons for
  515. disallowing pickles include security (loading pickled data can execute
  516. arbitrary code) and portability (pickled objects may not be loadable
  517. on different Python installations, for example if the stored objects
  518. require libraries that are not available, and not all pickled data is
  519. compatible between different versions of Python).
  520. Default: True
  521. kwds : Keyword arguments, optional
  522. Arrays to save to the file. Each array will be saved to the
  523. output file with its corresponding keyword name.
  524. Returns
  525. -------
  526. None
  527. See Also
  528. --------
  529. save : Save a single array to a binary file in NumPy format.
  530. savetxt : Save an array to a file as plain text.
  531. savez_compressed : Save several arrays into a compressed ``.npz`` archive
  532. Notes
  533. -----
  534. The ``.npz`` file format is a zipped archive of files named after the
  535. variables they contain. The archive is not compressed and each file
  536. in the archive contains one variable in ``.npy`` format. For a
  537. description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
  538. When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
  539. object is returned. This is a dictionary-like object which can be queried
  540. for its list of arrays (with the ``.files`` attribute), and for the arrays
  541. themselves.
  542. Keys passed in `kwds` are used as filenames inside the ZIP archive.
  543. Therefore, keys should be valid filenames; e.g., avoid keys that begin with
  544. ``/`` or contain ``.``.
  545. When naming variables with keyword arguments, it is not possible to name a
  546. variable ``file``, as this would cause the ``file`` argument to be defined
  547. twice in the call to ``savez``.
  548. Examples
  549. --------
  550. >>> import numpy as np
  551. >>> from tempfile import TemporaryFile
  552. >>> outfile = TemporaryFile()
  553. >>> x = np.arange(10)
  554. >>> y = np.sin(x)
  555. Using `savez` with \\*args, the arrays are saved with default names.
  556. >>> np.savez(outfile, x, y)
  557. >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
  558. >>> npzfile = np.load(outfile)
  559. >>> npzfile.files
  560. ['arr_0', 'arr_1']
  561. >>> npzfile['arr_0']
  562. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  563. Using `savez` with \\**kwds, the arrays are saved with the keyword names.
  564. >>> outfile = TemporaryFile()
  565. >>> np.savez(outfile, x=x, y=y)
  566. >>> _ = outfile.seek(0)
  567. >>> npzfile = np.load(outfile)
  568. >>> sorted(npzfile.files)
  569. ['x', 'y']
  570. >>> npzfile['x']
  571. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  572. """
  573. _savez(file, args, kwds, False, allow_pickle=allow_pickle)
  574. def _savez_compressed_dispatcher(file, *args, allow_pickle=True, **kwds):
  575. yield from args
  576. yield from kwds.values()
  577. @array_function_dispatch(_savez_compressed_dispatcher)
  578. def savez_compressed(file, *args, allow_pickle=True, **kwds):
  579. """
  580. Save several arrays into a single file in compressed ``.npz`` format.
  581. Provide arrays as keyword arguments to store them under the
  582. corresponding name in the output file: ``savez_compressed(fn, x=x, y=y)``.
  583. If arrays are specified as positional arguments, i.e.,
  584. ``savez_compressed(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc.
  585. Parameters
  586. ----------
  587. file : file, str, or pathlib.Path
  588. Either the filename (string) or an open file (file-like object)
  589. where the data will be saved. If file is a string or a Path, the
  590. ``.npz`` extension will be appended to the filename if it is not
  591. already there.
  592. args : Arguments, optional
  593. Arrays to save to the file. Please use keyword arguments (see
  594. `kwds` below) to assign names to arrays. Arrays specified as
  595. args will be named "arr_0", "arr_1", and so on.
  596. allow_pickle : bool, optional
  597. Allow saving object arrays using Python pickles. Reasons for
  598. disallowing pickles include security (loading pickled data can execute
  599. arbitrary code) and portability (pickled objects may not be loadable
  600. on different Python installations, for example if the stored objects
  601. require libraries that are not available, and not all pickled data is
  602. compatible between different versions of Python).
  603. Default: True
  604. kwds : Keyword arguments, optional
  605. Arrays to save to the file. Each array will be saved to the
  606. output file with its corresponding keyword name.
  607. Returns
  608. -------
  609. None
  610. See Also
  611. --------
  612. numpy.save : Save a single array to a binary file in NumPy format.
  613. numpy.savetxt : Save an array to a file as plain text.
  614. numpy.savez : Save several arrays into an uncompressed ``.npz`` file format
  615. numpy.load : Load the files created by savez_compressed.
  616. Notes
  617. -----
  618. The ``.npz`` file format is a zipped archive of files named after the
  619. variables they contain. The archive is compressed with
  620. ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable
  621. in ``.npy`` format. For a description of the ``.npy`` format, see
  622. :py:mod:`numpy.lib.format`.
  623. When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
  624. object is returned. This is a dictionary-like object which can be queried
  625. for its list of arrays (with the ``.files`` attribute), and for the arrays
  626. themselves.
  627. Examples
  628. --------
  629. >>> import numpy as np
  630. >>> test_array = np.random.rand(3, 2)
  631. >>> test_vector = np.random.rand(4)
  632. >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
  633. >>> loaded = np.load('/tmp/123.npz')
  634. >>> print(np.array_equal(test_array, loaded['a']))
  635. True
  636. >>> print(np.array_equal(test_vector, loaded['b']))
  637. True
  638. """
  639. _savez(file, args, kwds, True, allow_pickle=allow_pickle)
  640. def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None):
  641. # Import is postponed to here since zipfile depends on gzip, an optional
  642. # component of the so-called standard library.
  643. import zipfile
  644. if not hasattr(file, 'write'):
  645. file = os.fspath(file)
  646. if not file.endswith('.npz'):
  647. file = file + '.npz'
  648. namedict = kwds
  649. for i, val in enumerate(args):
  650. key = 'arr_%d' % i
  651. if key in namedict.keys():
  652. raise ValueError(
  653. f"Cannot use un-named variables and keyword {key}")
  654. namedict[key] = val
  655. if compress:
  656. compression = zipfile.ZIP_DEFLATED
  657. else:
  658. compression = zipfile.ZIP_STORED
  659. zipf = zipfile_factory(file, mode="w", compression=compression)
  660. try:
  661. for key, val in namedict.items():
  662. fname = key + '.npy'
  663. val = np.asanyarray(val)
  664. # always force zip64, gh-10776
  665. with zipf.open(fname, 'w', force_zip64=True) as fid:
  666. format.write_array(fid, val,
  667. allow_pickle=allow_pickle,
  668. pickle_kwargs=pickle_kwargs)
  669. finally:
  670. zipf.close()
  671. def _ensure_ndmin_ndarray_check_param(ndmin):
  672. """Just checks if the param ndmin is supported on
  673. _ensure_ndmin_ndarray. It is intended to be used as
  674. verification before running anything expensive.
  675. e.g. loadtxt, genfromtxt
  676. """
  677. # Check correctness of the values of `ndmin`
  678. if ndmin not in [0, 1, 2]:
  679. raise ValueError(f"Illegal value of ndmin keyword: {ndmin}")
  680. def _ensure_ndmin_ndarray(a, *, ndmin: int):
  681. """This is a helper function of loadtxt and genfromtxt to ensure
  682. proper minimum dimension as requested
  683. ndim : int. Supported values 1, 2, 3
  684. ^^ whenever this changes, keep in sync with
  685. _ensure_ndmin_ndarray_check_param
  686. """
  687. # Verify that the array has at least dimensions `ndmin`.
  688. # Tweak the size and shape of the arrays - remove extraneous dimensions
  689. if a.ndim > ndmin:
  690. a = np.squeeze(a)
  691. # and ensure we have the minimum number of dimensions asked for
  692. # - has to be in this order for the odd case ndmin=1, a.squeeze().ndim=0
  693. if a.ndim < ndmin:
  694. if ndmin == 1:
  695. a = np.atleast_1d(a)
  696. elif ndmin == 2:
  697. a = np.atleast_2d(a).T
  698. return a
  699. # amount of lines loadtxt reads in one chunk, can be overridden for testing
  700. _loadtxt_chunksize = 50000
  701. def _check_nonneg_int(value, name="argument"):
  702. try:
  703. operator.index(value)
  704. except TypeError:
  705. raise TypeError(f"{name} must be an integer") from None
  706. if value < 0:
  707. raise ValueError(f"{name} must be nonnegative")
  708. def _preprocess_comments(iterable, comments, encoding):
  709. """
  710. Generator that consumes a line iterated iterable and strips out the
  711. multiple (or multi-character) comments from lines.
  712. This is a pre-processing step to achieve feature parity with loadtxt
  713. (we assume that this feature is a nieche feature).
  714. """
  715. for line in iterable:
  716. if isinstance(line, bytes):
  717. # Need to handle conversion here, or the splitting would fail
  718. line = line.decode(encoding)
  719. for c in comments:
  720. line = line.split(c, 1)[0]
  721. yield line
  722. # The number of rows we read in one go if confronted with a parametric dtype
  723. _loadtxt_chunksize = 50000
  724. def _read(fname, *, delimiter=',', comment='#', quote='"',
  725. imaginary_unit='j', usecols=None, skiplines=0,
  726. max_rows=None, converters=None, ndmin=None, unpack=False,
  727. dtype=np.float64, encoding=None):
  728. r"""
  729. Read a NumPy array from a text file.
  730. This is a helper function for loadtxt.
  731. Parameters
  732. ----------
  733. fname : file, str, or pathlib.Path
  734. The filename or the file to be read.
  735. delimiter : str, optional
  736. Field delimiter of the fields in line of the file.
  737. Default is a comma, ','. If None any sequence of whitespace is
  738. considered a delimiter.
  739. comment : str or sequence of str or None, optional
  740. Character that begins a comment. All text from the comment
  741. character to the end of the line is ignored.
  742. Multiple comments or multiple-character comment strings are supported,
  743. but may be slower and `quote` must be empty if used.
  744. Use None to disable all use of comments.
  745. quote : str or None, optional
  746. Character that is used to quote string fields. Default is '"'
  747. (a double quote). Use None to disable quote support.
  748. imaginary_unit : str, optional
  749. Character that represent the imaginary unit `sqrt(-1)`.
  750. Default is 'j'.
  751. usecols : array_like, optional
  752. A one-dimensional array of integer column numbers. These are the
  753. columns from the file to be included in the array. If this value
  754. is not given, all the columns are used.
  755. skiplines : int, optional
  756. Number of lines to skip before interpreting the data in the file.
  757. max_rows : int, optional
  758. Maximum number of rows of data to read. Default is to read the
  759. entire file.
  760. converters : dict or callable, optional
  761. A function to parse all columns strings into the desired value, or
  762. a dictionary mapping column number to a parser function.
  763. E.g. if column 0 is a date string: ``converters = {0: datestr2num}``.
  764. Converters can also be used to provide a default value for missing
  765. data, e.g. ``converters = lambda s: float(s.strip() or 0)`` will
  766. convert empty fields to 0.
  767. Default: None
  768. ndmin : int, optional
  769. Minimum dimension of the array returned.
  770. Allowed values are 0, 1 or 2. Default is 0.
  771. unpack : bool, optional
  772. If True, the returned array is transposed, so that arguments may be
  773. unpacked using ``x, y, z = read(...)``. When used with a structured
  774. data-type, arrays are returned for each field. Default is False.
  775. dtype : numpy data type
  776. A NumPy dtype instance, can be a structured dtype to map to the
  777. columns of the file.
  778. encoding : str, optional
  779. Encoding used to decode the inputfile. The special value 'bytes'
  780. (the default) enables backwards-compatible behavior for `converters`,
  781. ensuring that inputs to the converter functions are encoded
  782. bytes objects. The special value 'bytes' has no additional effect if
  783. ``converters=None``. If encoding is ``'bytes'`` or ``None``, the
  784. default system encoding is used.
  785. Returns
  786. -------
  787. ndarray
  788. NumPy array.
  789. """
  790. # Handle special 'bytes' keyword for encoding
  791. byte_converters = False
  792. if encoding == 'bytes':
  793. encoding = None
  794. byte_converters = True
  795. if dtype is None:
  796. raise TypeError("a dtype must be provided.")
  797. dtype = np.dtype(dtype)
  798. read_dtype_via_object_chunks = None
  799. if dtype.kind in 'SUM' and dtype in {
  800. np.dtype("S0"), np.dtype("U0"), np.dtype("M8"), np.dtype("m8")}:
  801. # This is a legacy "flexible" dtype. We do not truly support
  802. # parametric dtypes currently (no dtype discovery step in the core),
  803. # but have to support these for backward compatibility.
  804. read_dtype_via_object_chunks = dtype
  805. dtype = np.dtype(object)
  806. if usecols is not None:
  807. # Allow usecols to be a single int or a sequence of ints, the C-code
  808. # handles the rest
  809. try:
  810. usecols = list(usecols)
  811. except TypeError:
  812. usecols = [usecols]
  813. _ensure_ndmin_ndarray_check_param(ndmin)
  814. if comment is None:
  815. comments = None
  816. else:
  817. # assume comments are a sequence of strings
  818. if "" in comment:
  819. raise ValueError(
  820. "comments cannot be an empty string. Use comments=None to "
  821. "disable comments."
  822. )
  823. comments = tuple(comment)
  824. comment = None
  825. if len(comments) == 0:
  826. comments = None # No comments at all
  827. elif len(comments) == 1:
  828. # If there is only one comment, and that comment has one character,
  829. # the normal parsing can deal with it just fine.
  830. if isinstance(comments[0], str) and len(comments[0]) == 1:
  831. comment = comments[0]
  832. comments = None
  833. # Input validation if there are multiple comment characters
  834. elif delimiter in comments:
  835. raise TypeError(
  836. f"Comment characters '{comments}' cannot include the "
  837. f"delimiter '{delimiter}'"
  838. )
  839. # comment is now either a 1 or 0 character string or a tuple:
  840. if comments is not None:
  841. # Note: An earlier version support two character comments (and could
  842. # have been extended to multiple characters, we assume this is
  843. # rare enough to not optimize for.
  844. if quote is not None:
  845. raise ValueError(
  846. "when multiple comments or a multi-character comment is "
  847. "given, quotes are not supported. In this case quotechar "
  848. "must be set to None.")
  849. if len(imaginary_unit) != 1:
  850. raise ValueError('len(imaginary_unit) must be 1.')
  851. _check_nonneg_int(skiplines)
  852. if max_rows is not None:
  853. _check_nonneg_int(max_rows)
  854. else:
  855. # Passing -1 to the C code means "read the entire file".
  856. max_rows = -1
  857. fh_closing_ctx = contextlib.nullcontext()
  858. filelike = False
  859. try:
  860. if isinstance(fname, os.PathLike):
  861. fname = os.fspath(fname)
  862. if isinstance(fname, str):
  863. fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
  864. if encoding is None:
  865. encoding = getattr(fh, 'encoding', 'latin1')
  866. fh_closing_ctx = contextlib.closing(fh)
  867. data = fh
  868. filelike = True
  869. else:
  870. if encoding is None:
  871. encoding = getattr(fname, 'encoding', 'latin1')
  872. data = iter(fname)
  873. except TypeError as e:
  874. raise ValueError(
  875. f"fname must be a string, filehandle, list of strings,\n"
  876. f"or generator. Got {type(fname)} instead.") from e
  877. with fh_closing_ctx:
  878. if comments is not None:
  879. if filelike:
  880. data = iter(data)
  881. filelike = False
  882. data = _preprocess_comments(data, comments, encoding)
  883. if read_dtype_via_object_chunks is None:
  884. arr = _load_from_filelike(
  885. data, delimiter=delimiter, comment=comment, quote=quote,
  886. imaginary_unit=imaginary_unit,
  887. usecols=usecols, skiplines=skiplines, max_rows=max_rows,
  888. converters=converters, dtype=dtype,
  889. encoding=encoding, filelike=filelike,
  890. byte_converters=byte_converters)
  891. else:
  892. # This branch reads the file into chunks of object arrays and then
  893. # casts them to the desired actual dtype. This ensures correct
  894. # string-length and datetime-unit discovery (like `arr.astype()`).
  895. # Due to chunking, certain error reports are less clear, currently.
  896. if filelike:
  897. data = iter(data) # cannot chunk when reading from file
  898. filelike = False
  899. c_byte_converters = False
  900. if read_dtype_via_object_chunks == "S":
  901. c_byte_converters = True # Use latin1 rather than ascii
  902. chunks = []
  903. while max_rows != 0:
  904. if max_rows < 0:
  905. chunk_size = _loadtxt_chunksize
  906. else:
  907. chunk_size = min(_loadtxt_chunksize, max_rows)
  908. next_arr = _load_from_filelike(
  909. data, delimiter=delimiter, comment=comment, quote=quote,
  910. imaginary_unit=imaginary_unit,
  911. usecols=usecols, skiplines=skiplines, max_rows=chunk_size,
  912. converters=converters, dtype=dtype,
  913. encoding=encoding, filelike=filelike,
  914. byte_converters=byte_converters,
  915. c_byte_converters=c_byte_converters)
  916. # Cast here already. We hope that this is better even for
  917. # large files because the storage is more compact. It could
  918. # be adapted (in principle the concatenate could cast).
  919. chunks.append(next_arr.astype(read_dtype_via_object_chunks))
  920. skiplines = 0 # Only have to skip for first chunk
  921. if max_rows >= 0:
  922. max_rows -= chunk_size
  923. if len(next_arr) < chunk_size:
  924. # There was less data than requested, so we are done.
  925. break
  926. # Need at least one chunk, but if empty, the last one may have
  927. # the wrong shape.
  928. if len(chunks) > 1 and len(chunks[-1]) == 0:
  929. del chunks[-1]
  930. if len(chunks) == 1:
  931. arr = chunks[0]
  932. else:
  933. arr = np.concatenate(chunks, axis=0)
  934. # NOTE: ndmin works as advertised for structured dtypes, but normally
  935. # these would return a 1D result plus the structured dimension,
  936. # so ndmin=2 adds a third dimension even when no squeezing occurs.
  937. # A `squeeze=False` could be a better solution (pandas uses squeeze).
  938. arr = _ensure_ndmin_ndarray(arr, ndmin=ndmin)
  939. if arr.shape:
  940. if arr.shape[0] == 0:
  941. warnings.warn(
  942. f'loadtxt: input contained no data: "{fname}"',
  943. category=UserWarning,
  944. stacklevel=3
  945. )
  946. if unpack:
  947. # Unpack structured dtypes if requested:
  948. dt = arr.dtype
  949. if dt.names is not None:
  950. # For structured arrays, return an array for each field.
  951. return [arr[field] for field in dt.names]
  952. else:
  953. return arr.T
  954. else:
  955. return arr
  956. @finalize_array_function_like
  957. @set_module('numpy')
  958. def loadtxt(fname, dtype=float, comments='#', delimiter=None,
  959. converters=None, skiprows=0, usecols=None, unpack=False,
  960. ndmin=0, encoding=None, max_rows=None, *, quotechar=None,
  961. like=None):
  962. r"""
  963. Load data from a text file.
  964. Parameters
  965. ----------
  966. fname : file, str, pathlib.Path, list of str, generator
  967. File, filename, list, or generator to read. If the filename
  968. extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
  969. that generators must return bytes or strings. The strings
  970. in a list or produced by a generator are treated as lines.
  971. dtype : data-type, optional
  972. Data-type of the resulting array; default: float. If this is a
  973. structured data-type, the resulting array will be 1-dimensional, and
  974. each row will be interpreted as an element of the array. In this
  975. case, the number of columns used must match the number of fields in
  976. the data-type.
  977. comments : str or sequence of str or None, optional
  978. The characters or list of characters used to indicate the start of a
  979. comment. None implies no comments. For backwards compatibility, byte
  980. strings will be decoded as 'latin1'. The default is '#'.
  981. delimiter : str, optional
  982. The character used to separate the values. For backwards compatibility,
  983. byte strings will be decoded as 'latin1'. The default is whitespace.
  984. .. versionchanged:: 1.23.0
  985. Only single character delimiters are supported. Newline characters
  986. cannot be used as the delimiter.
  987. converters : dict or callable, optional
  988. Converter functions to customize value parsing. If `converters` is
  989. callable, the function is applied to all columns, else it must be a
  990. dict that maps column number to a parser function.
  991. See examples for further details.
  992. Default: None.
  993. .. versionchanged:: 1.23.0
  994. The ability to pass a single callable to be applied to all columns
  995. was added.
  996. skiprows : int, optional
  997. Skip the first `skiprows` lines, including comments; default: 0.
  998. usecols : int or sequence, optional
  999. Which columns to read, with 0 being the first. For example,
  1000. ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
  1001. The default, None, results in all columns being read.
  1002. unpack : bool, optional
  1003. If True, the returned array is transposed, so that arguments may be
  1004. unpacked using ``x, y, z = loadtxt(...)``. When used with a
  1005. structured data-type, arrays are returned for each field.
  1006. Default is False.
  1007. ndmin : int, optional
  1008. The returned array will have at least `ndmin` dimensions.
  1009. Otherwise mono-dimensional axes will be squeezed.
  1010. Legal values: 0 (default), 1 or 2.
  1011. encoding : str, optional
  1012. Encoding used to decode the inputfile. Does not apply to input streams.
  1013. The special value 'bytes' enables backward compatibility workarounds
  1014. that ensures you receive byte arrays as results if possible and passes
  1015. 'latin1' encoded strings to converters. Override this value to receive
  1016. unicode arrays and pass strings as input to converters. If set to None
  1017. the system default is used. The default value is None.
  1018. .. versionchanged:: 2.0
  1019. Before NumPy 2, the default was ``'bytes'`` for Python 2
  1020. compatibility. The default is now ``None``.
  1021. max_rows : int, optional
  1022. Read `max_rows` rows of content after `skiprows` lines. The default is
  1023. to read all the rows. Note that empty rows containing no data such as
  1024. empty lines and comment lines are not counted towards `max_rows`,
  1025. while such lines are counted in `skiprows`.
  1026. .. versionchanged:: 1.23.0
  1027. Lines containing no data, including comment lines (e.g., lines
  1028. starting with '#' or as specified via `comments`) are not counted
  1029. towards `max_rows`.
  1030. quotechar : unicode character or None, optional
  1031. The character used to denote the start and end of a quoted item.
  1032. Occurrences of the delimiter or comment characters are ignored within
  1033. a quoted item. The default value is ``quotechar=None``, which means
  1034. quoting support is disabled.
  1035. If two consecutive instances of `quotechar` are found within a quoted
  1036. field, the first is treated as an escape character. See examples.
  1037. .. versionadded:: 1.23.0
  1038. ${ARRAY_FUNCTION_LIKE}
  1039. .. versionadded:: 1.20.0
  1040. Returns
  1041. -------
  1042. out : ndarray
  1043. Data read from the text file.
  1044. See Also
  1045. --------
  1046. load, fromstring, fromregex
  1047. genfromtxt : Load data with missing values handled as specified.
  1048. scipy.io.loadmat : reads MATLAB data files
  1049. Notes
  1050. -----
  1051. This function aims to be a fast reader for simply formatted files. The
  1052. `genfromtxt` function provides more sophisticated handling of, e.g.,
  1053. lines with missing values.
  1054. Each row in the input text file must have the same number of values to be
  1055. able to read all values. If all rows do not have same number of values, a
  1056. subset of up to n columns (where n is the least number of values present
  1057. in all rows) can be read by specifying the columns via `usecols`.
  1058. The strings produced by the Python float.hex method can be used as
  1059. input for floats.
  1060. Examples
  1061. --------
  1062. >>> import numpy as np
  1063. >>> from io import StringIO # StringIO behaves like a file object
  1064. >>> c = StringIO("0 1\n2 3")
  1065. >>> np.loadtxt(c)
  1066. array([[0., 1.],
  1067. [2., 3.]])
  1068. >>> d = StringIO("M 21 72\nF 35 58")
  1069. >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
  1070. ... 'formats': ('S1', 'i4', 'f4')})
  1071. array([(b'M', 21, 72.), (b'F', 35, 58.)],
  1072. dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])
  1073. >>> c = StringIO("1,0,2\n3,0,4")
  1074. >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
  1075. >>> x
  1076. array([1., 3.])
  1077. >>> y
  1078. array([2., 4.])
  1079. The `converters` argument is used to specify functions to preprocess the
  1080. text prior to parsing. `converters` can be a dictionary that maps
  1081. preprocessing functions to each column:
  1082. >>> s = StringIO("1.618, 2.296\n3.141, 4.669\n")
  1083. >>> conv = {
  1084. ... 0: lambda x: np.floor(float(x)), # conversion fn for column 0
  1085. ... 1: lambda x: np.ceil(float(x)), # conversion fn for column 1
  1086. ... }
  1087. >>> np.loadtxt(s, delimiter=",", converters=conv)
  1088. array([[1., 3.],
  1089. [3., 5.]])
  1090. `converters` can be a callable instead of a dictionary, in which case it
  1091. is applied to all columns:
  1092. >>> s = StringIO("0xDE 0xAD\n0xC0 0xDE")
  1093. >>> import functools
  1094. >>> conv = functools.partial(int, base=16)
  1095. >>> np.loadtxt(s, converters=conv)
  1096. array([[222., 173.],
  1097. [192., 222.]])
  1098. This example shows how `converters` can be used to convert a field
  1099. with a trailing minus sign into a negative number.
  1100. >>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94")
  1101. >>> def conv(fld):
  1102. ... return -float(fld[:-1]) if fld.endswith("-") else float(fld)
  1103. ...
  1104. >>> np.loadtxt(s, converters=conv)
  1105. array([[ 10.01, -31.25],
  1106. [ 19.22, 64.31],
  1107. [-17.57, 63.94]])
  1108. Using a callable as the converter can be particularly useful for handling
  1109. values with different formatting, e.g. floats with underscores:
  1110. >>> s = StringIO("1 2.7 100_000")
  1111. >>> np.loadtxt(s, converters=float)
  1112. array([1.e+00, 2.7e+00, 1.e+05])
  1113. This idea can be extended to automatically handle values specified in
  1114. many different formats, such as hex values:
  1115. >>> def conv(val):
  1116. ... try:
  1117. ... return float(val)
  1118. ... except ValueError:
  1119. ... return float.fromhex(val)
  1120. >>> s = StringIO("1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2")
  1121. >>> np.loadtxt(s, delimiter=",", converters=conv)
  1122. array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00])
  1123. Or a format where the ``-`` sign comes after the number:
  1124. >>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94")
  1125. >>> conv = lambda x: -float(x[:-1]) if x.endswith("-") else float(x)
  1126. >>> np.loadtxt(s, converters=conv)
  1127. array([[ 10.01, -31.25],
  1128. [ 19.22, 64.31],
  1129. [-17.57, 63.94]])
  1130. Support for quoted fields is enabled with the `quotechar` parameter.
  1131. Comment and delimiter characters are ignored when they appear within a
  1132. quoted item delineated by `quotechar`:
  1133. >>> s = StringIO('"alpha, #42", 10.0\n"beta, #64", 2.0\n')
  1134. >>> dtype = np.dtype([("label", "U12"), ("value", float)])
  1135. >>> np.loadtxt(s, dtype=dtype, delimiter=",", quotechar='"')
  1136. array([('alpha, #42', 10.), ('beta, #64', 2.)],
  1137. dtype=[('label', '<U12'), ('value', '<f8')])
  1138. Quoted fields can be separated by multiple whitespace characters:
  1139. >>> s = StringIO('"alpha, #42" 10.0\n"beta, #64" 2.0\n')
  1140. >>> dtype = np.dtype([("label", "U12"), ("value", float)])
  1141. >>> np.loadtxt(s, dtype=dtype, delimiter=None, quotechar='"')
  1142. array([('alpha, #42', 10.), ('beta, #64', 2.)],
  1143. dtype=[('label', '<U12'), ('value', '<f8')])
  1144. Two consecutive quote characters within a quoted field are treated as a
  1145. single escaped character:
  1146. >>> s = StringIO('"Hello, my name is ""Monty""!"')
  1147. >>> np.loadtxt(s, dtype="U", delimiter=",", quotechar='"')
  1148. array('Hello, my name is "Monty"!', dtype='<U26')
  1149. Read subset of columns when all rows do not contain equal number of values:
  1150. >>> d = StringIO("1 2\n2 4\n3 9 12\n4 16 20")
  1151. >>> np.loadtxt(d, usecols=(0, 1))
  1152. array([[ 1., 2.],
  1153. [ 2., 4.],
  1154. [ 3., 9.],
  1155. [ 4., 16.]])
  1156. """
  1157. if like is not None:
  1158. return _loadtxt_with_like(
  1159. like, fname, dtype=dtype, comments=comments, delimiter=delimiter,
  1160. converters=converters, skiprows=skiprows, usecols=usecols,
  1161. unpack=unpack, ndmin=ndmin, encoding=encoding,
  1162. max_rows=max_rows
  1163. )
  1164. if isinstance(delimiter, bytes):
  1165. delimiter.decode("latin1")
  1166. if dtype is None:
  1167. dtype = np.float64
  1168. comment = comments
  1169. # Control character type conversions for Py3 convenience
  1170. if comment is not None:
  1171. if isinstance(comment, (str, bytes)):
  1172. comment = [comment]
  1173. comment = [
  1174. x.decode('latin1') if isinstance(x, bytes) else x for x in comment]
  1175. if isinstance(delimiter, bytes):
  1176. delimiter = delimiter.decode('latin1')
  1177. arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter,
  1178. converters=converters, skiplines=skiprows, usecols=usecols,
  1179. unpack=unpack, ndmin=ndmin, encoding=encoding,
  1180. max_rows=max_rows, quote=quotechar)
  1181. return arr
  1182. _loadtxt_with_like = array_function_dispatch()(loadtxt)
  1183. def _savetxt_dispatcher(fname, X, fmt=None, delimiter=None, newline=None,
  1184. header=None, footer=None, comments=None,
  1185. encoding=None):
  1186. return (X,)
  1187. @array_function_dispatch(_savetxt_dispatcher)
  1188. def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
  1189. footer='', comments='# ', encoding=None):
  1190. """
  1191. Save an array to a text file.
  1192. Parameters
  1193. ----------
  1194. fname : filename, file handle or pathlib.Path
  1195. If the filename ends in ``.gz``, the file is automatically saved in
  1196. compressed gzip format. `loadtxt` understands gzipped files
  1197. transparently.
  1198. X : 1D or 2D array_like
  1199. Data to be saved to a text file.
  1200. fmt : str or sequence of strs, optional
  1201. A single format (%10.5f), a sequence of formats, or a
  1202. multi-format string, e.g. 'Iteration %d -- %10.5f', in which
  1203. case `delimiter` is ignored. For complex `X`, the legal options
  1204. for `fmt` are:
  1205. * a single specifier, ``fmt='%.4e'``, resulting in numbers formatted
  1206. like ``' (%s+%sj)' % (fmt, fmt)``
  1207. * a full string specifying every real and imaginary part, e.g.
  1208. ``' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'`` for 3 columns
  1209. * a list of specifiers, one per column - in this case, the real
  1210. and imaginary part must have separate specifiers,
  1211. e.g. ``['%.3e + %.3ej', '(%.15e%+.15ej)']`` for 2 columns
  1212. delimiter : str, optional
  1213. String or character separating columns.
  1214. newline : str, optional
  1215. String or character separating lines.
  1216. header : str, optional
  1217. String that will be written at the beginning of the file.
  1218. footer : str, optional
  1219. String that will be written at the end of the file.
  1220. comments : str, optional
  1221. String that will be prepended to the ``header`` and ``footer`` strings,
  1222. to mark them as comments. Default: '# ', as expected by e.g.
  1223. ``numpy.loadtxt``.
  1224. encoding : {None, str}, optional
  1225. Encoding used to encode the outputfile. Does not apply to output
  1226. streams. If the encoding is something other than 'bytes' or 'latin1'
  1227. you will not be able to load the file in NumPy versions < 1.14. Default
  1228. is 'latin1'.
  1229. See Also
  1230. --------
  1231. save : Save an array to a binary file in NumPy ``.npy`` format
  1232. savez : Save several arrays into an uncompressed ``.npz`` archive
  1233. savez_compressed : Save several arrays into a compressed ``.npz`` archive
  1234. Notes
  1235. -----
  1236. Further explanation of the `fmt` parameter
  1237. (``%[flag]width[.precision]specifier``):
  1238. flags:
  1239. ``-`` : left justify
  1240. ``+`` : Forces to precede result with + or -.
  1241. ``0`` : Left pad the number with zeros instead of space (see width).
  1242. width:
  1243. Minimum number of characters to be printed. The value is not truncated
  1244. if it has more characters.
  1245. precision:
  1246. - For integer specifiers (eg. ``d,i,o,x``), the minimum number of
  1247. digits.
  1248. - For ``e, E`` and ``f`` specifiers, the number of digits to print
  1249. after the decimal point.
  1250. - For ``g`` and ``G``, the maximum number of significant digits.
  1251. - For ``s``, the maximum number of characters.
  1252. specifiers:
  1253. ``c`` : character
  1254. ``d`` or ``i`` : signed decimal integer
  1255. ``e`` or ``E`` : scientific notation with ``e`` or ``E``.
  1256. ``f`` : decimal floating point
  1257. ``g,G`` : use the shorter of ``e,E`` or ``f``
  1258. ``o`` : signed octal
  1259. ``s`` : string of characters
  1260. ``u`` : unsigned decimal integer
  1261. ``x,X`` : unsigned hexadecimal integer
  1262. This explanation of ``fmt`` is not complete, for an exhaustive
  1263. specification see [1]_.
  1264. References
  1265. ----------
  1266. .. [1] `Format Specification Mini-Language
  1267. <https://docs.python.org/library/string.html#format-specification-mini-language>`_,
  1268. Python Documentation.
  1269. Examples
  1270. --------
  1271. >>> import numpy as np
  1272. >>> x = y = z = np.arange(0.0,5.0,1.0)
  1273. >>> np.savetxt('test.out', x, delimiter=',') # X is an array
  1274. >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays
  1275. >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation
  1276. """
  1277. class WriteWrap:
  1278. """Convert to bytes on bytestream inputs.
  1279. """
  1280. def __init__(self, fh, encoding):
  1281. self.fh = fh
  1282. self.encoding = encoding
  1283. self.do_write = self.first_write
  1284. def close(self):
  1285. self.fh.close()
  1286. def write(self, v):
  1287. self.do_write(v)
  1288. def write_bytes(self, v):
  1289. if isinstance(v, bytes):
  1290. self.fh.write(v)
  1291. else:
  1292. self.fh.write(v.encode(self.encoding))
  1293. def write_normal(self, v):
  1294. self.fh.write(asunicode(v))
  1295. def first_write(self, v):
  1296. try:
  1297. self.write_normal(v)
  1298. self.write = self.write_normal
  1299. except TypeError:
  1300. # input is probably a bytestream
  1301. self.write_bytes(v)
  1302. self.write = self.write_bytes
  1303. own_fh = False
  1304. if isinstance(fname, os.PathLike):
  1305. fname = os.fspath(fname)
  1306. if _is_string_like(fname):
  1307. # datasource doesn't support creating a new file ...
  1308. open(fname, 'wt').close()
  1309. fh = np.lib._datasource.open(fname, 'wt', encoding=encoding)
  1310. own_fh = True
  1311. elif hasattr(fname, 'write'):
  1312. # wrap to handle byte output streams
  1313. fh = WriteWrap(fname, encoding or 'latin1')
  1314. else:
  1315. raise ValueError('fname must be a string or file handle')
  1316. try:
  1317. X = np.asarray(X)
  1318. # Handle 1-dimensional arrays
  1319. if X.ndim == 0 or X.ndim > 2:
  1320. raise ValueError(
  1321. "Expected 1D or 2D array, got %dD array instead" % X.ndim)
  1322. elif X.ndim == 1:
  1323. # Common case -- 1d array of numbers
  1324. if X.dtype.names is None:
  1325. X = np.atleast_2d(X).T
  1326. ncol = 1
  1327. # Complex dtype -- each field indicates a separate column
  1328. else:
  1329. ncol = len(X.dtype.names)
  1330. else:
  1331. ncol = X.shape[1]
  1332. iscomplex_X = np.iscomplexobj(X)
  1333. # `fmt` can be a string with multiple insertion points or a
  1334. # list of formats. E.g. '%10.5f\t%10d' or ('%10.5f', '$10d')
  1335. if type(fmt) in (list, tuple):
  1336. if len(fmt) != ncol:
  1337. raise AttributeError(f'fmt has wrong shape. {str(fmt)}')
  1338. format = delimiter.join(fmt)
  1339. elif isinstance(fmt, str):
  1340. n_fmt_chars = fmt.count('%')
  1341. error = ValueError(f'fmt has wrong number of % formats: {fmt}')
  1342. if n_fmt_chars == 1:
  1343. if iscomplex_X:
  1344. fmt = [f' ({fmt}+{fmt}j)', ] * ncol
  1345. else:
  1346. fmt = [fmt, ] * ncol
  1347. format = delimiter.join(fmt)
  1348. elif iscomplex_X and n_fmt_chars != (2 * ncol):
  1349. raise error
  1350. elif ((not iscomplex_X) and n_fmt_chars != ncol):
  1351. raise error
  1352. else:
  1353. format = fmt
  1354. else:
  1355. raise ValueError(f'invalid fmt: {fmt!r}')
  1356. if len(header) > 0:
  1357. header = header.replace('\n', '\n' + comments)
  1358. fh.write(comments + header + newline)
  1359. if iscomplex_X:
  1360. for row in X:
  1361. row2 = []
  1362. for number in row:
  1363. row2.extend((number.real, number.imag))
  1364. s = format % tuple(row2) + newline
  1365. fh.write(s.replace('+-', '-'))
  1366. else:
  1367. for row in X:
  1368. try:
  1369. v = format % tuple(row) + newline
  1370. except TypeError as e:
  1371. raise TypeError("Mismatch between array dtype ('%s') and "
  1372. "format specifier ('%s')"
  1373. % (str(X.dtype), format)) from e
  1374. fh.write(v)
  1375. if len(footer) > 0:
  1376. footer = footer.replace('\n', '\n' + comments)
  1377. fh.write(comments + footer + newline)
  1378. finally:
  1379. if own_fh:
  1380. fh.close()
  1381. @set_module('numpy')
  1382. def fromregex(file, regexp, dtype, encoding=None):
  1383. r"""
  1384. Construct an array from a text file, using regular expression parsing.
  1385. The returned array is always a structured array, and is constructed from
  1386. all matches of the regular expression in the file. Groups in the regular
  1387. expression are converted to fields of the structured array.
  1388. Parameters
  1389. ----------
  1390. file : file, str, or pathlib.Path
  1391. Filename or file object to read.
  1392. .. versionchanged:: 1.22.0
  1393. Now accepts `os.PathLike` implementations.
  1394. regexp : str or regexp
  1395. Regular expression used to parse the file.
  1396. Groups in the regular expression correspond to fields in the dtype.
  1397. dtype : dtype or list of dtypes
  1398. Dtype for the structured array; must be a structured datatype.
  1399. encoding : str, optional
  1400. Encoding used to decode the inputfile. Does not apply to input streams.
  1401. Returns
  1402. -------
  1403. output : ndarray
  1404. The output array, containing the part of the content of `file` that
  1405. was matched by `regexp`. `output` is always a structured array.
  1406. Raises
  1407. ------
  1408. TypeError
  1409. When `dtype` is not a valid dtype for a structured array.
  1410. See Also
  1411. --------
  1412. fromstring, loadtxt
  1413. Notes
  1414. -----
  1415. Dtypes for structured arrays can be specified in several forms, but all
  1416. forms specify at least the data type and field name. For details see
  1417. `basics.rec`.
  1418. Examples
  1419. --------
  1420. >>> import numpy as np
  1421. >>> from io import StringIO
  1422. >>> text = StringIO("1312 foo\n1534 bar\n444 qux")
  1423. >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything]
  1424. >>> output = np.fromregex(text, regexp,
  1425. ... [('num', np.int64), ('key', 'S3')])
  1426. >>> output
  1427. array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
  1428. dtype=[('num', '<i8'), ('key', 'S3')])
  1429. >>> output['num']
  1430. array([1312, 1534, 444])
  1431. """
  1432. own_fh = False
  1433. if not hasattr(file, "read"):
  1434. file = os.fspath(file)
  1435. file = np.lib._datasource.open(file, 'rt', encoding=encoding)
  1436. own_fh = True
  1437. try:
  1438. if not isinstance(dtype, np.dtype):
  1439. dtype = np.dtype(dtype)
  1440. if dtype.names is None:
  1441. raise TypeError('dtype must be a structured datatype.')
  1442. content = file.read()
  1443. if isinstance(content, bytes) and isinstance(regexp, str):
  1444. regexp = asbytes(regexp)
  1445. if not hasattr(regexp, 'match'):
  1446. regexp = re.compile(regexp)
  1447. seq = regexp.findall(content)
  1448. if seq and not isinstance(seq[0], tuple):
  1449. # Only one group is in the regexp.
  1450. # Create the new array as a single data-type and then
  1451. # re-interpret as a single-field structured array.
  1452. newdtype = np.dtype(dtype[dtype.names[0]])
  1453. output = np.array(seq, dtype=newdtype)
  1454. output = output.view(dtype)
  1455. else:
  1456. output = np.array(seq, dtype=dtype)
  1457. return output
  1458. finally:
  1459. if own_fh:
  1460. file.close()
  1461. #####--------------------------------------------------------------------------
  1462. #---- --- ASCII functions ---
  1463. #####--------------------------------------------------------------------------
  1464. @finalize_array_function_like
  1465. @set_module('numpy')
  1466. def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
  1467. skip_header=0, skip_footer=0, converters=None,
  1468. missing_values=None, filling_values=None, usecols=None,
  1469. names=None, excludelist=None,
  1470. deletechars=''.join(sorted(NameValidator.defaultdeletechars)), # noqa: B008
  1471. replace_space='_', autostrip=False, case_sensitive=True,
  1472. defaultfmt="f%i", unpack=None, usemask=False, loose=True,
  1473. invalid_raise=True, max_rows=None, encoding=None,
  1474. *, ndmin=0, like=None):
  1475. """
  1476. Load data from a text file, with missing values handled as specified.
  1477. Each line past the first `skip_header` lines is split at the `delimiter`
  1478. character, and characters following the `comments` character are discarded.
  1479. Parameters
  1480. ----------
  1481. fname : file, str, pathlib.Path, list of str, generator
  1482. File, filename, list, or generator to read. If the filename
  1483. extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
  1484. that generators must return bytes or strings. The strings
  1485. in a list or produced by a generator are treated as lines.
  1486. dtype : dtype, optional
  1487. Data type of the resulting array.
  1488. If None, the dtypes will be determined by the contents of each
  1489. column, individually.
  1490. comments : str, optional
  1491. The character used to indicate the start of a comment.
  1492. All the characters occurring on a line after a comment are discarded.
  1493. delimiter : str, int, or sequence, optional
  1494. The string used to separate values. By default, any consecutive
  1495. whitespaces act as delimiter. An integer or sequence of integers
  1496. can also be provided as width(s) of each field.
  1497. skiprows : int, optional
  1498. `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
  1499. skip_header : int, optional
  1500. The number of lines to skip at the beginning of the file.
  1501. skip_footer : int, optional
  1502. The number of lines to skip at the end of the file.
  1503. converters : variable, optional
  1504. The set of functions that convert the data of a column to a value.
  1505. The converters can also be used to provide a default value
  1506. for missing data: ``converters = {3: lambda s: float(s or 0)}``.
  1507. missing : variable, optional
  1508. `missing` was removed in numpy 1.10. Please use `missing_values`
  1509. instead.
  1510. missing_values : variable, optional
  1511. The set of strings corresponding to missing data.
  1512. filling_values : variable, optional
  1513. The set of values to be used as default when the data are missing.
  1514. usecols : sequence, optional
  1515. Which columns to read, with 0 being the first. For example,
  1516. ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
  1517. names : {None, True, str, sequence}, optional
  1518. If `names` is True, the field names are read from the first line after
  1519. the first `skip_header` lines. This line can optionally be preceded
  1520. by a comment delimiter. Any content before the comment delimiter is
  1521. discarded. If `names` is a sequence or a single-string of
  1522. comma-separated names, the names will be used to define the field
  1523. names in a structured dtype. If `names` is None, the names of the
  1524. dtype fields will be used, if any.
  1525. excludelist : sequence, optional
  1526. A list of names to exclude. This list is appended to the default list
  1527. ['return','file','print']. Excluded names are appended with an
  1528. underscore: for example, `file` would become `file_`.
  1529. deletechars : str, optional
  1530. A string combining invalid characters that must be deleted from the
  1531. names.
  1532. defaultfmt : str, optional
  1533. A format used to define default field names, such as "f%i" or "f_%02i".
  1534. autostrip : bool, optional
  1535. Whether to automatically strip white spaces from the variables.
  1536. replace_space : char, optional
  1537. Character(s) used in replacement of white spaces in the variable
  1538. names. By default, use a '_'.
  1539. case_sensitive : {True, False, 'upper', 'lower'}, optional
  1540. If True, field names are case sensitive.
  1541. If False or 'upper', field names are converted to upper case.
  1542. If 'lower', field names are converted to lower case.
  1543. unpack : bool, optional
  1544. If True, the returned array is transposed, so that arguments may be
  1545. unpacked using ``x, y, z = genfromtxt(...)``. When used with a
  1546. structured data-type, arrays are returned for each field.
  1547. Default is False.
  1548. usemask : bool, optional
  1549. If True, return a masked array.
  1550. If False, return a regular array.
  1551. loose : bool, optional
  1552. If True, do not raise errors for invalid values.
  1553. invalid_raise : bool, optional
  1554. If True, an exception is raised if an inconsistency is detected in the
  1555. number of columns.
  1556. If False, a warning is emitted and the offending lines are skipped.
  1557. max_rows : int, optional
  1558. The maximum number of rows to read. Must not be used with skip_footer
  1559. at the same time. If given, the value must be at least 1. Default is
  1560. to read the entire file.
  1561. encoding : str, optional
  1562. Encoding used to decode the inputfile. Does not apply when `fname`
  1563. is a file object. The special value 'bytes' enables backward
  1564. compatibility workarounds that ensure that you receive byte arrays
  1565. when possible and passes latin1 encoded strings to converters.
  1566. Override this value to receive unicode arrays and pass strings
  1567. as input to converters. If set to None the system default is used.
  1568. The default value is 'bytes'.
  1569. .. versionchanged:: 2.0
  1570. Before NumPy 2, the default was ``'bytes'`` for Python 2
  1571. compatibility. The default is now ``None``.
  1572. ndmin : int, optional
  1573. Same parameter as `loadtxt`
  1574. .. versionadded:: 1.23.0
  1575. ${ARRAY_FUNCTION_LIKE}
  1576. .. versionadded:: 1.20.0
  1577. Returns
  1578. -------
  1579. out : ndarray
  1580. Data read from the text file. If `usemask` is True, this is a
  1581. masked array.
  1582. See Also
  1583. --------
  1584. numpy.loadtxt : equivalent function when no data is missing.
  1585. Notes
  1586. -----
  1587. * When spaces are used as delimiters, or when no delimiter has been given
  1588. as input, there should not be any missing data between two fields.
  1589. * When variables are named (either by a flexible dtype or with a `names`
  1590. sequence), there must not be any header in the file (else a ValueError
  1591. exception is raised).
  1592. * Individual values are not stripped of spaces by default.
  1593. When using a custom converter, make sure the function does remove spaces.
  1594. * Custom converters may receive unexpected values due to dtype
  1595. discovery.
  1596. References
  1597. ----------
  1598. .. [1] NumPy User Guide, section `I/O with NumPy
  1599. <https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.
  1600. Examples
  1601. --------
  1602. >>> from io import StringIO
  1603. >>> import numpy as np
  1604. Comma delimited file with mixed dtype
  1605. >>> s = StringIO("1,1.3,abcde")
  1606. >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
  1607. ... ('mystring','S5')], delimiter=",")
  1608. >>> data
  1609. array((1, 1.3, b'abcde'),
  1610. dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
  1611. Using dtype = None
  1612. >>> _ = s.seek(0) # needed for StringIO example only
  1613. >>> data = np.genfromtxt(s, dtype=None,
  1614. ... names = ['myint','myfloat','mystring'], delimiter=",")
  1615. >>> data
  1616. array((1, 1.3, 'abcde'),
  1617. dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '<U5')])
  1618. Specifying dtype and names
  1619. >>> _ = s.seek(0)
  1620. >>> data = np.genfromtxt(s, dtype="i8,f8,S5",
  1621. ... names=['myint','myfloat','mystring'], delimiter=",")
  1622. >>> data
  1623. array((1, 1.3, b'abcde'),
  1624. dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
  1625. An example with fixed-width columns
  1626. >>> s = StringIO("11.3abcde")
  1627. >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
  1628. ... delimiter=[1,3,5])
  1629. >>> data
  1630. array((1, 1.3, 'abcde'),
  1631. dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '<U5')])
  1632. An example to show comments
  1633. >>> f = StringIO('''
  1634. ... text,# of chars
  1635. ... hello world,11
  1636. ... numpy,5''')
  1637. >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',')
  1638. array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')],
  1639. dtype=[('f0', 'S12'), ('f1', 'S12')])
  1640. """
  1641. if like is not None:
  1642. return _genfromtxt_with_like(
  1643. like, fname, dtype=dtype, comments=comments, delimiter=delimiter,
  1644. skip_header=skip_header, skip_footer=skip_footer,
  1645. converters=converters, missing_values=missing_values,
  1646. filling_values=filling_values, usecols=usecols, names=names,
  1647. excludelist=excludelist, deletechars=deletechars,
  1648. replace_space=replace_space, autostrip=autostrip,
  1649. case_sensitive=case_sensitive, defaultfmt=defaultfmt,
  1650. unpack=unpack, usemask=usemask, loose=loose,
  1651. invalid_raise=invalid_raise, max_rows=max_rows, encoding=encoding,
  1652. ndmin=ndmin,
  1653. )
  1654. _ensure_ndmin_ndarray_check_param(ndmin)
  1655. if max_rows is not None:
  1656. if skip_footer:
  1657. raise ValueError(
  1658. "The keywords 'skip_footer' and 'max_rows' can not be "
  1659. "specified at the same time.")
  1660. if max_rows < 1:
  1661. raise ValueError("'max_rows' must be at least 1.")
  1662. if usemask:
  1663. from numpy.ma import MaskedArray, make_mask_descr
  1664. # Check the input dictionary of converters
  1665. user_converters = converters or {}
  1666. if not isinstance(user_converters, dict):
  1667. raise TypeError(
  1668. "The input argument 'converter' should be a valid dictionary "
  1669. "(got '%s' instead)" % type(user_converters))
  1670. if encoding == 'bytes':
  1671. encoding = None
  1672. byte_converters = True
  1673. else:
  1674. byte_converters = False
  1675. # Initialize the filehandle, the LineSplitter and the NameValidator
  1676. if isinstance(fname, os.PathLike):
  1677. fname = os.fspath(fname)
  1678. if isinstance(fname, str):
  1679. fid = np.lib._datasource.open(fname, 'rt', encoding=encoding)
  1680. fid_ctx = contextlib.closing(fid)
  1681. else:
  1682. fid = fname
  1683. fid_ctx = contextlib.nullcontext(fid)
  1684. try:
  1685. fhd = iter(fid)
  1686. except TypeError as e:
  1687. raise TypeError(
  1688. "fname must be a string, a filehandle, a sequence of strings,\n"
  1689. f"or an iterator of strings. Got {type(fname)} instead."
  1690. ) from e
  1691. with fid_ctx:
  1692. split_line = LineSplitter(delimiter=delimiter, comments=comments,
  1693. autostrip=autostrip, encoding=encoding)
  1694. validate_names = NameValidator(excludelist=excludelist,
  1695. deletechars=deletechars,
  1696. case_sensitive=case_sensitive,
  1697. replace_space=replace_space)
  1698. # Skip the first `skip_header` rows
  1699. try:
  1700. for i in range(skip_header):
  1701. next(fhd)
  1702. # Keep on until we find the first valid values
  1703. first_values = None
  1704. while not first_values:
  1705. first_line = _decode_line(next(fhd), encoding)
  1706. if (names is True) and (comments is not None):
  1707. if comments in first_line:
  1708. first_line = (
  1709. ''.join(first_line.split(comments)[1:]))
  1710. first_values = split_line(first_line)
  1711. except StopIteration:
  1712. # return an empty array if the datafile is empty
  1713. first_line = ''
  1714. first_values = []
  1715. warnings.warn(
  1716. f'genfromtxt: Empty input file: "{fname}"', stacklevel=2
  1717. )
  1718. # Should we take the first values as names ?
  1719. if names is True:
  1720. fval = first_values[0].strip()
  1721. if comments is not None:
  1722. if fval in comments:
  1723. del first_values[0]
  1724. # Check the columns to use: make sure `usecols` is a list
  1725. if usecols is not None:
  1726. try:
  1727. usecols = [_.strip() for _ in usecols.split(",")]
  1728. except AttributeError:
  1729. try:
  1730. usecols = list(usecols)
  1731. except TypeError:
  1732. usecols = [usecols, ]
  1733. nbcols = len(usecols or first_values)
  1734. # Check the names and overwrite the dtype.names if needed
  1735. if names is True:
  1736. names = validate_names([str(_.strip()) for _ in first_values])
  1737. first_line = ''
  1738. elif _is_string_like(names):
  1739. names = validate_names([_.strip() for _ in names.split(',')])
  1740. elif names:
  1741. names = validate_names(names)
  1742. # Get the dtype
  1743. if dtype is not None:
  1744. dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names,
  1745. excludelist=excludelist,
  1746. deletechars=deletechars,
  1747. case_sensitive=case_sensitive,
  1748. replace_space=replace_space)
  1749. # Make sure the names is a list (for 2.5)
  1750. if names is not None:
  1751. names = list(names)
  1752. if usecols:
  1753. for (i, current) in enumerate(usecols):
  1754. # if usecols is a list of names, convert to a list of indices
  1755. if _is_string_like(current):
  1756. usecols[i] = names.index(current)
  1757. elif current < 0:
  1758. usecols[i] = current + len(first_values)
  1759. # If the dtype is not None, make sure we update it
  1760. if (dtype is not None) and (len(dtype) > nbcols):
  1761. descr = dtype.descr
  1762. dtype = np.dtype([descr[_] for _ in usecols])
  1763. names = list(dtype.names)
  1764. # If `names` is not None, update the names
  1765. elif (names is not None) and (len(names) > nbcols):
  1766. names = [names[_] for _ in usecols]
  1767. elif (names is not None) and (dtype is not None):
  1768. names = list(dtype.names)
  1769. # Process the missing values ...............................
  1770. # Rename missing_values for convenience
  1771. user_missing_values = missing_values or ()
  1772. if isinstance(user_missing_values, bytes):
  1773. user_missing_values = user_missing_values.decode('latin1')
  1774. # Define the list of missing_values (one column: one list)
  1775. missing_values = [[''] for _ in range(nbcols)]
  1776. # We have a dictionary: process it field by field
  1777. if isinstance(user_missing_values, dict):
  1778. # Loop on the items
  1779. for (key, val) in user_missing_values.items():
  1780. # Is the key a string ?
  1781. if _is_string_like(key):
  1782. try:
  1783. # Transform it into an integer
  1784. key = names.index(key)
  1785. except ValueError:
  1786. # We couldn't find it: the name must have been dropped
  1787. continue
  1788. # Redefine the key as needed if it's a column number
  1789. if usecols:
  1790. try:
  1791. key = usecols.index(key)
  1792. except ValueError:
  1793. pass
  1794. # Transform the value as a list of string
  1795. if isinstance(val, (list, tuple)):
  1796. val = [str(_) for _ in val]
  1797. else:
  1798. val = [str(val), ]
  1799. # Add the value(s) to the current list of missing
  1800. if key is None:
  1801. # None acts as default
  1802. for miss in missing_values:
  1803. miss.extend(val)
  1804. else:
  1805. missing_values[key].extend(val)
  1806. # We have a sequence : each item matches a column
  1807. elif isinstance(user_missing_values, (list, tuple)):
  1808. for (value, entry) in zip(user_missing_values, missing_values):
  1809. value = str(value)
  1810. if value not in entry:
  1811. entry.append(value)
  1812. # We have a string : apply it to all entries
  1813. elif isinstance(user_missing_values, str):
  1814. user_value = user_missing_values.split(",")
  1815. for entry in missing_values:
  1816. entry.extend(user_value)
  1817. # We have something else: apply it to all entries
  1818. else:
  1819. for entry in missing_values:
  1820. entry.extend([str(user_missing_values)])
  1821. # Process the filling_values ...............................
  1822. # Rename the input for convenience
  1823. user_filling_values = filling_values
  1824. if user_filling_values is None:
  1825. user_filling_values = []
  1826. # Define the default
  1827. filling_values = [None] * nbcols
  1828. # We have a dictionary : update each entry individually
  1829. if isinstance(user_filling_values, dict):
  1830. for (key, val) in user_filling_values.items():
  1831. if _is_string_like(key):
  1832. try:
  1833. # Transform it into an integer
  1834. key = names.index(key)
  1835. except ValueError:
  1836. # We couldn't find it: the name must have been dropped
  1837. continue
  1838. # Redefine the key if it's a column number
  1839. # and usecols is defined
  1840. if usecols:
  1841. try:
  1842. key = usecols.index(key)
  1843. except ValueError:
  1844. pass
  1845. # Add the value to the list
  1846. filling_values[key] = val
  1847. # We have a sequence : update on a one-to-one basis
  1848. elif isinstance(user_filling_values, (list, tuple)):
  1849. n = len(user_filling_values)
  1850. if (n <= nbcols):
  1851. filling_values[:n] = user_filling_values
  1852. else:
  1853. filling_values = user_filling_values[:nbcols]
  1854. # We have something else : use it for all entries
  1855. else:
  1856. filling_values = [user_filling_values] * nbcols
  1857. # Initialize the converters ................................
  1858. if dtype is None:
  1859. # Note: we can't use a [...]*nbcols, as we would have 3 times
  1860. # the same converter, instead of 3 different converters.
  1861. converters = [
  1862. StringConverter(None, missing_values=miss, default=fill)
  1863. for (miss, fill) in zip(missing_values, filling_values)
  1864. ]
  1865. else:
  1866. dtype_flat = flatten_dtype(dtype, flatten_base=True)
  1867. # Initialize the converters
  1868. if len(dtype_flat) > 1:
  1869. # Flexible type : get a converter from each dtype
  1870. zipit = zip(dtype_flat, missing_values, filling_values)
  1871. converters = [StringConverter(dt,
  1872. locked=True,
  1873. missing_values=miss,
  1874. default=fill)
  1875. for (dt, miss, fill) in zipit]
  1876. else:
  1877. # Set to a default converter (but w/ different missing values)
  1878. zipit = zip(missing_values, filling_values)
  1879. converters = [StringConverter(dtype,
  1880. locked=True,
  1881. missing_values=miss,
  1882. default=fill)
  1883. for (miss, fill) in zipit]
  1884. # Update the converters to use the user-defined ones
  1885. uc_update = []
  1886. for (j, conv) in user_converters.items():
  1887. # If the converter is specified by column names,
  1888. # use the index instead
  1889. if _is_string_like(j):
  1890. try:
  1891. j = names.index(j)
  1892. i = j
  1893. except ValueError:
  1894. continue
  1895. elif usecols:
  1896. try:
  1897. i = usecols.index(j)
  1898. except ValueError:
  1899. # Unused converter specified
  1900. continue
  1901. else:
  1902. i = j
  1903. # Find the value to test - first_line is not filtered by usecols:
  1904. if len(first_line):
  1905. testing_value = first_values[j]
  1906. else:
  1907. testing_value = None
  1908. if conv is bytes:
  1909. user_conv = asbytes
  1910. elif byte_converters:
  1911. # Converters may use decode to workaround numpy's old
  1912. # behavior, so encode the string again before passing
  1913. # to the user converter.
  1914. def tobytes_first(x, conv):
  1915. if type(x) is bytes:
  1916. return conv(x)
  1917. return conv(x.encode("latin1"))
  1918. user_conv = functools.partial(tobytes_first, conv=conv)
  1919. else:
  1920. user_conv = conv
  1921. converters[i].update(user_conv, locked=True,
  1922. testing_value=testing_value,
  1923. default=filling_values[i],
  1924. missing_values=missing_values[i],)
  1925. uc_update.append((i, user_conv))
  1926. # Make sure we have the corrected keys in user_converters...
  1927. user_converters.update(uc_update)
  1928. # Fixme: possible error as following variable never used.
  1929. # miss_chars = [_.missing_values for _ in converters]
  1930. # Initialize the output lists ...
  1931. # ... rows
  1932. rows = []
  1933. append_to_rows = rows.append
  1934. # ... masks
  1935. if usemask:
  1936. masks = []
  1937. append_to_masks = masks.append
  1938. # ... invalid
  1939. invalid = []
  1940. append_to_invalid = invalid.append
  1941. # Parse each line
  1942. for (i, line) in enumerate(itertools.chain([first_line, ], fhd)):
  1943. values = split_line(line)
  1944. nbvalues = len(values)
  1945. # Skip an empty line
  1946. if nbvalues == 0:
  1947. continue
  1948. if usecols:
  1949. # Select only the columns we need
  1950. try:
  1951. values = [values[_] for _ in usecols]
  1952. except IndexError:
  1953. append_to_invalid((i + skip_header + 1, nbvalues))
  1954. continue
  1955. elif nbvalues != nbcols:
  1956. append_to_invalid((i + skip_header + 1, nbvalues))
  1957. continue
  1958. # Store the values
  1959. append_to_rows(tuple(values))
  1960. if usemask:
  1961. append_to_masks(tuple(v.strip() in m
  1962. for (v, m) in zip(values,
  1963. missing_values)))
  1964. if len(rows) == max_rows:
  1965. break
  1966. # Upgrade the converters (if needed)
  1967. if dtype is None:
  1968. for (i, converter) in enumerate(converters):
  1969. current_column = [itemgetter(i)(_m) for _m in rows]
  1970. try:
  1971. converter.iterupgrade(current_column)
  1972. except ConverterLockError:
  1973. errmsg = f"Converter #{i} is locked and cannot be upgraded: "
  1974. current_column = map(itemgetter(i), rows)
  1975. for (j, value) in enumerate(current_column):
  1976. try:
  1977. converter.upgrade(value)
  1978. except (ConverterError, ValueError):
  1979. line_number = j + 1 + skip_header
  1980. errmsg += f"(occurred line #{line_number} for value '{value}')"
  1981. raise ConverterError(errmsg)
  1982. # Check that we don't have invalid values
  1983. nbinvalid = len(invalid)
  1984. if nbinvalid > 0:
  1985. nbrows = len(rows) + nbinvalid - skip_footer
  1986. # Construct the error message
  1987. template = f" Line #%i (got %i columns instead of {nbcols})"
  1988. if skip_footer > 0:
  1989. nbinvalid_skipped = len([_ for _ in invalid
  1990. if _[0] > nbrows + skip_header])
  1991. invalid = invalid[:nbinvalid - nbinvalid_skipped]
  1992. skip_footer -= nbinvalid_skipped
  1993. #
  1994. # nbrows -= skip_footer
  1995. # errmsg = [template % (i, nb)
  1996. # for (i, nb) in invalid if i < nbrows]
  1997. # else:
  1998. errmsg = [template % (i, nb)
  1999. for (i, nb) in invalid]
  2000. if len(errmsg):
  2001. errmsg.insert(0, "Some errors were detected !")
  2002. errmsg = "\n".join(errmsg)
  2003. # Raise an exception ?
  2004. if invalid_raise:
  2005. raise ValueError(errmsg)
  2006. # Issue a warning ?
  2007. else:
  2008. warnings.warn(errmsg, ConversionWarning, stacklevel=2)
  2009. # Strip the last skip_footer data
  2010. if skip_footer > 0:
  2011. rows = rows[:-skip_footer]
  2012. if usemask:
  2013. masks = masks[:-skip_footer]
  2014. # Convert each value according to the converter:
  2015. # We want to modify the list in place to avoid creating a new one...
  2016. if loose:
  2017. rows = list(
  2018. zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)]
  2019. for (i, conv) in enumerate(converters)]))
  2020. else:
  2021. rows = list(
  2022. zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)]
  2023. for (i, conv) in enumerate(converters)]))
  2024. # Reset the dtype
  2025. data = rows
  2026. if dtype is None:
  2027. # Get the dtypes from the types of the converters
  2028. column_types = [conv.type for conv in converters]
  2029. # Find the columns with strings...
  2030. strcolidx = [i for (i, v) in enumerate(column_types)
  2031. if v == np.str_]
  2032. if byte_converters and strcolidx:
  2033. # convert strings back to bytes for backward compatibility
  2034. warnings.warn(
  2035. "Reading unicode strings without specifying the encoding "
  2036. "argument is deprecated. Set the encoding, use None for the "
  2037. "system default.",
  2038. np.exceptions.VisibleDeprecationWarning, stacklevel=2)
  2039. def encode_unicode_cols(row_tup):
  2040. row = list(row_tup)
  2041. for i in strcolidx:
  2042. row[i] = row[i].encode('latin1')
  2043. return tuple(row)
  2044. try:
  2045. data = [encode_unicode_cols(r) for r in data]
  2046. except UnicodeEncodeError:
  2047. pass
  2048. else:
  2049. for i in strcolidx:
  2050. column_types[i] = np.bytes_
  2051. # Update string types to be the right length
  2052. sized_column_types = column_types.copy()
  2053. for i, col_type in enumerate(column_types):
  2054. if np.issubdtype(col_type, np.character):
  2055. n_chars = max(len(row[i]) for row in data)
  2056. sized_column_types[i] = (col_type, n_chars)
  2057. if names is None:
  2058. # If the dtype is uniform (before sizing strings)
  2059. base = {
  2060. c_type
  2061. for c, c_type in zip(converters, column_types)
  2062. if c._checked}
  2063. if len(base) == 1:
  2064. uniform_type, = base
  2065. (ddtype, mdtype) = (uniform_type, bool)
  2066. else:
  2067. ddtype = [(defaultfmt % i, dt)
  2068. for (i, dt) in enumerate(sized_column_types)]
  2069. if usemask:
  2070. mdtype = [(defaultfmt % i, bool)
  2071. for (i, dt) in enumerate(sized_column_types)]
  2072. else:
  2073. ddtype = list(zip(names, sized_column_types))
  2074. mdtype = list(zip(names, [bool] * len(sized_column_types)))
  2075. output = np.array(data, dtype=ddtype)
  2076. if usemask:
  2077. outputmask = np.array(masks, dtype=mdtype)
  2078. else:
  2079. # Overwrite the initial dtype names if needed
  2080. if names and dtype.names is not None:
  2081. dtype.names = names
  2082. # Case 1. We have a structured type
  2083. if len(dtype_flat) > 1:
  2084. # Nested dtype, eg [('a', int), ('b', [('b0', int), ('b1', 'f4')])]
  2085. # First, create the array using a flattened dtype:
  2086. # [('a', int), ('b1', int), ('b2', float)]
  2087. # Then, view the array using the specified dtype.
  2088. if 'O' in (_.char for _ in dtype_flat):
  2089. if has_nested_fields(dtype):
  2090. raise NotImplementedError(
  2091. "Nested fields involving objects are not supported...")
  2092. else:
  2093. output = np.array(data, dtype=dtype)
  2094. else:
  2095. rows = np.array(data, dtype=[('', _) for _ in dtype_flat])
  2096. output = rows.view(dtype)
  2097. # Now, process the rowmasks the same way
  2098. if usemask:
  2099. rowmasks = np.array(
  2100. masks, dtype=np.dtype([('', bool) for t in dtype_flat]))
  2101. # Construct the new dtype
  2102. mdtype = make_mask_descr(dtype)
  2103. outputmask = rowmasks.view(mdtype)
  2104. # Case #2. We have a basic dtype
  2105. else:
  2106. # We used some user-defined converters
  2107. if user_converters:
  2108. ishomogeneous = True
  2109. descr = []
  2110. for i, ttype in enumerate([conv.type for conv in converters]):
  2111. # Keep the dtype of the current converter
  2112. if i in user_converters:
  2113. ishomogeneous &= (ttype == dtype.type)
  2114. if np.issubdtype(ttype, np.character):
  2115. ttype = (ttype, max(len(row[i]) for row in data))
  2116. descr.append(('', ttype))
  2117. else:
  2118. descr.append(('', dtype))
  2119. # So we changed the dtype ?
  2120. if not ishomogeneous:
  2121. # We have more than one field
  2122. if len(descr) > 1:
  2123. dtype = np.dtype(descr)
  2124. # We have only one field: drop the name if not needed.
  2125. else:
  2126. dtype = np.dtype(ttype)
  2127. #
  2128. output = np.array(data, dtype)
  2129. if usemask:
  2130. if dtype.names is not None:
  2131. mdtype = [(_, bool) for _ in dtype.names]
  2132. else:
  2133. mdtype = bool
  2134. outputmask = np.array(masks, dtype=mdtype)
  2135. # Try to take care of the missing data we missed
  2136. names = output.dtype.names
  2137. if usemask and names:
  2138. for (name, conv) in zip(names, converters):
  2139. missing_values = [conv(_) for _ in conv.missing_values
  2140. if _ != '']
  2141. for mval in missing_values:
  2142. outputmask[name] |= (output[name] == mval)
  2143. # Construct the final array
  2144. if usemask:
  2145. output = output.view(MaskedArray)
  2146. output._mask = outputmask
  2147. output = _ensure_ndmin_ndarray(output, ndmin=ndmin)
  2148. if unpack:
  2149. if names is None:
  2150. return output.T
  2151. elif len(names) == 1:
  2152. # squeeze single-name dtypes too
  2153. return output[names[0]]
  2154. else:
  2155. # For structured arrays with multiple fields,
  2156. # return an array for each field.
  2157. return [output[field] for field in names]
  2158. return output
  2159. _genfromtxt_with_like = array_function_dispatch()(genfromtxt)
  2160. def recfromtxt(fname, **kwargs):
  2161. """
  2162. Load ASCII data from a file and return it in a record array.
  2163. If ``usemask=False`` a standard `recarray` is returned,
  2164. if ``usemask=True`` a MaskedRecords array is returned.
  2165. .. deprecated:: 2.0
  2166. Use `numpy.genfromtxt` instead.
  2167. Parameters
  2168. ----------
  2169. fname, kwargs : For a description of input parameters, see `genfromtxt`.
  2170. See Also
  2171. --------
  2172. numpy.genfromtxt : generic function
  2173. Notes
  2174. -----
  2175. By default, `dtype` is None, which means that the data-type of the output
  2176. array will be determined from the data.
  2177. """
  2178. # Deprecated in NumPy 2.0, 2023-07-11
  2179. warnings.warn(
  2180. "`recfromtxt` is deprecated, "
  2181. "use `numpy.genfromtxt` instead."
  2182. "(deprecated in NumPy 2.0)",
  2183. DeprecationWarning,
  2184. stacklevel=2
  2185. )
  2186. kwargs.setdefault("dtype", None)
  2187. usemask = kwargs.get('usemask', False)
  2188. output = genfromtxt(fname, **kwargs)
  2189. if usemask:
  2190. from numpy.ma.mrecords import MaskedRecords
  2191. output = output.view(MaskedRecords)
  2192. else:
  2193. output = output.view(np.recarray)
  2194. return output
  2195. def recfromcsv(fname, **kwargs):
  2196. """
  2197. Load ASCII data stored in a comma-separated file.
  2198. The returned array is a record array (if ``usemask=False``, see
  2199. `recarray`) or a masked record array (if ``usemask=True``,
  2200. see `ma.mrecords.MaskedRecords`).
  2201. .. deprecated:: 2.0
  2202. Use `numpy.genfromtxt` with comma as `delimiter` instead.
  2203. Parameters
  2204. ----------
  2205. fname, kwargs : For a description of input parameters, see `genfromtxt`.
  2206. See Also
  2207. --------
  2208. numpy.genfromtxt : generic function to load ASCII data.
  2209. Notes
  2210. -----
  2211. By default, `dtype` is None, which means that the data-type of the output
  2212. array will be determined from the data.
  2213. """
  2214. # Deprecated in NumPy 2.0, 2023-07-11
  2215. warnings.warn(
  2216. "`recfromcsv` is deprecated, "
  2217. "use `numpy.genfromtxt` with comma as `delimiter` instead. "
  2218. "(deprecated in NumPy 2.0)",
  2219. DeprecationWarning,
  2220. stacklevel=2
  2221. )
  2222. # Set default kwargs for genfromtxt as relevant to csv import.
  2223. kwargs.setdefault("case_sensitive", "lower")
  2224. kwargs.setdefault("names", True)
  2225. kwargs.setdefault("delimiter", ",")
  2226. kwargs.setdefault("dtype", None)
  2227. output = genfromtxt(fname, **kwargs)
  2228. usemask = kwargs.get("usemask", False)
  2229. if usemask:
  2230. from numpy.ma.mrecords import MaskedRecords
  2231. output = output.view(MaskedRecords)
  2232. else:
  2233. output = output.view(np.recarray)
  2234. return output