npyio.py 95 KB

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