_npyio_impl.py 97 KB

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