readers.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. """
  2. Module contains tools for processing files into DataFrames or other objects
  3. GH#48849 provides a convenient way of deprecating keyword arguments
  4. """
  5. from __future__ import annotations
  6. from collections import abc
  7. import csv
  8. import sys
  9. from textwrap import fill
  10. from types import TracebackType
  11. from typing import (
  12. IO,
  13. Any,
  14. Callable,
  15. Hashable,
  16. Literal,
  17. NamedTuple,
  18. Sequence,
  19. overload,
  20. )
  21. import warnings
  22. import numpy as np
  23. from pandas._libs import lib
  24. from pandas._libs.parsers import STR_NA_VALUES
  25. from pandas._typing import (
  26. CompressionOptions,
  27. CSVEngine,
  28. DtypeArg,
  29. DtypeBackend,
  30. FilePath,
  31. IndexLabel,
  32. ReadCsvBuffer,
  33. StorageOptions,
  34. )
  35. from pandas.errors import (
  36. AbstractMethodError,
  37. ParserWarning,
  38. )
  39. from pandas.util._decorators import Appender
  40. from pandas.util._exceptions import find_stack_level
  41. from pandas.util._validators import check_dtype_backend
  42. from pandas.core.dtypes.common import (
  43. is_file_like,
  44. is_float,
  45. is_integer,
  46. is_list_like,
  47. )
  48. from pandas.core.frame import DataFrame
  49. from pandas.core.indexes.api import RangeIndex
  50. from pandas.core.shared_docs import _shared_docs
  51. from pandas.io.common import (
  52. IOHandles,
  53. get_handle,
  54. stringify_path,
  55. validate_header_arg,
  56. )
  57. from pandas.io.parsers.arrow_parser_wrapper import ArrowParserWrapper
  58. from pandas.io.parsers.base_parser import (
  59. ParserBase,
  60. is_index_col,
  61. parser_defaults,
  62. )
  63. from pandas.io.parsers.c_parser_wrapper import CParserWrapper
  64. from pandas.io.parsers.python_parser import (
  65. FixedWidthFieldParser,
  66. PythonParser,
  67. )
  68. _doc_read_csv_and_table = (
  69. r"""
  70. {summary}
  71. Also supports optionally iterating or breaking of the file
  72. into chunks.
  73. Additional help can be found in the online docs for
  74. `IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.
  75. Parameters
  76. ----------
  77. filepath_or_buffer : str, path object or file-like object
  78. Any valid string path is acceptable. The string could be a URL. Valid
  79. URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is
  80. expected. A local file could be: file://localhost/path/to/table.csv.
  81. If you want to pass in a path object, pandas accepts any ``os.PathLike``.
  82. By file-like object, we refer to objects with a ``read()`` method, such as
  83. a file handle (e.g. via builtin ``open`` function) or ``StringIO``.
  84. sep : str, default {_default_sep}
  85. Delimiter to use. If sep is None, the C engine cannot automatically detect
  86. the separator, but the Python parsing engine can, meaning the latter will
  87. be used and automatically detect the separator by Python's builtin sniffer
  88. tool, ``csv.Sniffer``. In addition, separators longer than 1 character and
  89. different from ``'\s+'`` will be interpreted as regular expressions and
  90. will also force the use of the Python parsing engine. Note that regex
  91. delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``.
  92. delimiter : str, default ``None``
  93. Alias for sep.
  94. header : int, list of int, None, default 'infer'
  95. Row number(s) to use as the column names, and the start of the
  96. data. Default behavior is to infer the column names: if no names
  97. are passed the behavior is identical to ``header=0`` and column
  98. names are inferred from the first line of the file, if column
  99. names are passed explicitly then the behavior is identical to
  100. ``header=None``. Explicitly pass ``header=0`` to be able to
  101. replace existing names. The header can be a list of integers that
  102. specify row locations for a multi-index on the columns
  103. e.g. [0,1,3]. Intervening rows that are not specified will be
  104. skipped (e.g. 2 in this example is skipped). Note that this
  105. parameter ignores commented lines and empty lines if
  106. ``skip_blank_lines=True``, so ``header=0`` denotes the first line of
  107. data rather than the first line of the file.
  108. names : array-like, optional
  109. List of column names to use. If the file contains a header row,
  110. then you should explicitly pass ``header=0`` to override the column names.
  111. Duplicates in this list are not allowed.
  112. index_col : int, str, sequence of int / str, or False, optional, default ``None``
  113. Column(s) to use as the row labels of the ``DataFrame``, either given as
  114. string name or column index. If a sequence of int / str is given, a
  115. MultiIndex is used.
  116. Note: ``index_col=False`` can be used to force pandas to *not* use the first
  117. column as the index, e.g. when you have a malformed file with delimiters at
  118. the end of each line.
  119. usecols : list-like or callable, optional
  120. Return a subset of the columns. If list-like, all elements must either
  121. be positional (i.e. integer indices into the document columns) or strings
  122. that correspond to column names provided either by the user in `names` or
  123. inferred from the document header row(s). If ``names`` are given, the document
  124. header row(s) are not taken into account. For example, a valid list-like
  125. `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
  126. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
  127. To instantiate a DataFrame from ``data`` with element order preserved use
  128. ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns
  129. in ``['foo', 'bar']`` order or
  130. ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``
  131. for ``['bar', 'foo']`` order.
  132. If callable, the callable function will be evaluated against the column
  133. names, returning names where the callable function evaluates to True. An
  134. example of a valid callable argument would be ``lambda x: x.upper() in
  135. ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster
  136. parsing time and lower memory usage.
  137. dtype : Type name or dict of column -> type, optional
  138. Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32,
  139. 'c': 'Int64'}}
  140. Use `str` or `object` together with suitable `na_values` settings
  141. to preserve and not interpret dtype.
  142. If converters are specified, they will be applied INSTEAD
  143. of dtype conversion.
  144. .. versionadded:: 1.5.0
  145. Support for defaultdict was added. Specify a defaultdict as input where
  146. the default determines the dtype of the columns which are not explicitly
  147. listed.
  148. engine : {{'c', 'python', 'pyarrow'}}, optional
  149. Parser engine to use. The C and pyarrow engines are faster, while the python engine
  150. is currently more feature-complete. Multithreading is currently only supported by
  151. the pyarrow engine.
  152. .. versionadded:: 1.4.0
  153. The "pyarrow" engine was added as an *experimental* engine, and some features
  154. are unsupported, or may not work correctly, with this engine.
  155. converters : dict, optional
  156. Dict of functions for converting values in certain columns. Keys can either
  157. be integers or column labels.
  158. true_values : list, optional
  159. Values to consider as True in addition to case-insensitive variants of "True".
  160. false_values : list, optional
  161. Values to consider as False in addition to case-insensitive variants of "False".
  162. skipinitialspace : bool, default False
  163. Skip spaces after delimiter.
  164. skiprows : list-like, int or callable, optional
  165. Line numbers to skip (0-indexed) or number of lines to skip (int)
  166. at the start of the file.
  167. If callable, the callable function will be evaluated against the row
  168. indices, returning True if the row should be skipped and False otherwise.
  169. An example of a valid callable argument would be ``lambda x: x in [0, 2]``.
  170. skipfooter : int, default 0
  171. Number of lines at bottom of file to skip (Unsupported with engine='c').
  172. nrows : int, optional
  173. Number of rows of file to read. Useful for reading pieces of large files.
  174. na_values : scalar, str, list-like, or dict, optional
  175. Additional strings to recognize as NA/NaN. If dict passed, specific
  176. per-column NA values. By default the following values are interpreted as
  177. NaN: '"""
  178. + fill("', '".join(sorted(STR_NA_VALUES)), 70, subsequent_indent=" ")
  179. + """'.
  180. keep_default_na : bool, default True
  181. Whether or not to include the default NaN values when parsing the data.
  182. Depending on whether `na_values` is passed in, the behavior is as follows:
  183. * If `keep_default_na` is True, and `na_values` are specified, `na_values`
  184. is appended to the default NaN values used for parsing.
  185. * If `keep_default_na` is True, and `na_values` are not specified, only
  186. the default NaN values are used for parsing.
  187. * If `keep_default_na` is False, and `na_values` are specified, only
  188. the NaN values specified `na_values` are used for parsing.
  189. * If `keep_default_na` is False, and `na_values` are not specified, no
  190. strings will be parsed as NaN.
  191. Note that if `na_filter` is passed in as False, the `keep_default_na` and
  192. `na_values` parameters will be ignored.
  193. na_filter : bool, default True
  194. Detect missing value markers (empty strings and the value of na_values). In
  195. data without any NAs, passing na_filter=False can improve the performance
  196. of reading a large file.
  197. verbose : bool, default False
  198. Indicate number of NA values placed in non-numeric columns.
  199. skip_blank_lines : bool, default True
  200. If True, skip over blank lines rather than interpreting as NaN values.
  201. parse_dates : bool or list of int or names or list of lists or dict, \
  202. default False
  203. The behavior is as follows:
  204. * boolean. If True -> try parsing the index.
  205. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
  206. each as a separate date column.
  207. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
  208. a single date column.
  209. * dict, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call
  210. result 'foo'
  211. If a column or index cannot be represented as an array of datetimes,
  212. say because of an unparsable value or a mixture of timezones, the column
  213. or index will be returned unaltered as an object data type. For
  214. non-standard datetime parsing, use ``pd.to_datetime`` after
  215. ``pd.read_csv``.
  216. Note: A fast-path exists for iso8601-formatted dates.
  217. infer_datetime_format : bool, default False
  218. If True and `parse_dates` is enabled, pandas will attempt to infer the
  219. format of the datetime strings in the columns, and if it can be inferred,
  220. switch to a faster method of parsing them. In some cases this can increase
  221. the parsing speed by 5-10x.
  222. .. deprecated:: 2.0.0
  223. A strict version of this argument is now the default, passing it has no effect.
  224. keep_date_col : bool, default False
  225. If True and `parse_dates` specifies combining multiple columns then
  226. keep the original columns.
  227. date_parser : function, optional
  228. Function to use for converting a sequence of string columns to an array of
  229. datetime instances. The default uses ``dateutil.parser.parser`` to do the
  230. conversion. Pandas will try to call `date_parser` in three different ways,
  231. advancing to the next if an exception occurs: 1) Pass one or more arrays
  232. (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the
  233. string values from the columns defined by `parse_dates` into a single array
  234. and pass that; and 3) call `date_parser` once for each row using one or
  235. more strings (corresponding to the columns defined by `parse_dates`) as
  236. arguments.
  237. .. deprecated:: 2.0.0
  238. Use ``date_format`` instead, or read in as ``object`` and then apply
  239. :func:`to_datetime` as-needed.
  240. date_format : str or dict of column -> format, default ``None``
  241. If used in conjunction with ``parse_dates``, will parse dates according to this
  242. format. For anything more complex,
  243. please read in as ``object`` and then apply :func:`to_datetime` as-needed.
  244. .. versionadded:: 2.0.0
  245. dayfirst : bool, default False
  246. DD/MM format dates, international and European format.
  247. cache_dates : bool, default True
  248. If True, use a cache of unique, converted dates to apply the datetime
  249. conversion. May produce significant speed-up when parsing duplicate
  250. date strings, especially ones with timezone offsets.
  251. iterator : bool, default False
  252. Return TextFileReader object for iteration or getting chunks with
  253. ``get_chunk()``.
  254. .. versionchanged:: 1.2
  255. ``TextFileReader`` is a context manager.
  256. chunksize : int, optional
  257. Return TextFileReader object for iteration.
  258. See the `IO Tools docs
  259. <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_
  260. for more information on ``iterator`` and ``chunksize``.
  261. .. versionchanged:: 1.2
  262. ``TextFileReader`` is a context manager.
  263. {decompression_options}
  264. .. versionchanged:: 1.4.0 Zstandard support.
  265. thousands : str, optional
  266. Thousands separator.
  267. decimal : str, default '.'
  268. Character to recognize as decimal point (e.g. use ',' for European data).
  269. lineterminator : str (length 1), optional
  270. Character to break file into lines. Only valid with C parser.
  271. quotechar : str (length 1), optional
  272. The character used to denote the start and end of a quoted item. Quoted
  273. items can include the delimiter and it will be ignored.
  274. quoting : int or csv.QUOTE_* instance, default 0
  275. Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of
  276. QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
  277. doublequote : bool, default ``True``
  278. When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate
  279. whether or not to interpret two consecutive quotechar elements INSIDE a
  280. field as a single ``quotechar`` element.
  281. escapechar : str (length 1), optional
  282. One-character string used to escape other characters.
  283. comment : str, optional
  284. Indicates remainder of line should not be parsed. If found at the beginning
  285. of a line, the line will be ignored altogether. This parameter must be a
  286. single character. Like empty lines (as long as ``skip_blank_lines=True``),
  287. fully commented lines are ignored by the parameter `header` but not by
  288. `skiprows`. For example, if ``comment='#'``, parsing
  289. ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in 'a,b,c' being
  290. treated as the header.
  291. encoding : str, optional, default "utf-8"
  292. Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
  293. standard encodings
  294. <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .
  295. .. versionchanged:: 1.2
  296. When ``encoding`` is ``None``, ``errors="replace"`` is passed to
  297. ``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``.
  298. This behavior was previously only the case for ``engine="python"``.
  299. .. versionchanged:: 1.3.0
  300. ``encoding_errors`` is a new argument. ``encoding`` has no longer an
  301. influence on how encoding errors are handled.
  302. encoding_errors : str, optional, default "strict"
  303. How encoding errors are treated. `List of possible values
  304. <https://docs.python.org/3/library/codecs.html#error-handlers>`_ .
  305. .. versionadded:: 1.3.0
  306. dialect : str or csv.Dialect, optional
  307. If provided, this parameter will override values (default or not) for the
  308. following parameters: `delimiter`, `doublequote`, `escapechar`,
  309. `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to
  310. override values, a ParserWarning will be issued. See csv.Dialect
  311. documentation for more details.
  312. on_bad_lines : {{'error', 'warn', 'skip'}} or callable, default 'error'
  313. Specifies what to do upon encountering a bad line (a line with too many fields).
  314. Allowed values are :
  315. - 'error', raise an Exception when a bad line is encountered.
  316. - 'warn', raise a warning when a bad line is encountered and skip that line.
  317. - 'skip', skip bad lines without raising or warning when they are encountered.
  318. .. versionadded:: 1.3.0
  319. .. versionadded:: 1.4.0
  320. - callable, function with signature
  321. ``(bad_line: list[str]) -> list[str] | None`` that will process a single
  322. bad line. ``bad_line`` is a list of strings split by the ``sep``.
  323. If the function returns ``None``, the bad line will be ignored.
  324. If the function returns a new list of strings with more elements than
  325. expected, a ``ParserWarning`` will be emitted while dropping extra elements.
  326. Only supported when ``engine="python"``
  327. delim_whitespace : bool, default False
  328. Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be
  329. used as the sep. Equivalent to setting ``sep='\\s+'``. If this option
  330. is set to True, nothing should be passed in for the ``delimiter``
  331. parameter.
  332. low_memory : bool, default True
  333. Internally process the file in chunks, resulting in lower memory use
  334. while parsing, but possibly mixed type inference. To ensure no mixed
  335. types either set False, or specify the type with the `dtype` parameter.
  336. Note that the entire file is read into a single DataFrame regardless,
  337. use the `chunksize` or `iterator` parameter to return the data in chunks.
  338. (Only valid with C parser).
  339. memory_map : bool, default False
  340. If a filepath is provided for `filepath_or_buffer`, map the file object
  341. directly onto memory and access the data directly from there. Using this
  342. option can improve performance because there is no longer any I/O overhead.
  343. float_precision : str, optional
  344. Specifies which converter the C engine should use for floating-point
  345. values. The options are ``None`` or 'high' for the ordinary converter,
  346. 'legacy' for the original lower precision pandas converter, and
  347. 'round_trip' for the round-trip converter.
  348. .. versionchanged:: 1.2
  349. {storage_options}
  350. .. versionadded:: 1.2
  351. dtype_backend : {{"numpy_nullable", "pyarrow"}}, defaults to NumPy backed DataFrames
  352. Which dtype_backend to use, e.g. whether a DataFrame should have NumPy
  353. arrays, nullable dtypes are used for all dtypes that have a nullable
  354. implementation when "numpy_nullable" is set, pyarrow is used for all
  355. dtypes if "pyarrow" is set.
  356. The dtype_backends are still experimential.
  357. .. versionadded:: 2.0
  358. Returns
  359. -------
  360. DataFrame or TextFileReader
  361. A comma-separated values (csv) file is returned as two-dimensional
  362. data structure with labeled axes.
  363. See Also
  364. --------
  365. DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
  366. read_csv : Read a comma-separated values (csv) file into DataFrame.
  367. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
  368. Examples
  369. --------
  370. >>> pd.{func_name}('data.csv') # doctest: +SKIP
  371. """
  372. )
  373. _c_parser_defaults = {
  374. "delim_whitespace": False,
  375. "na_filter": True,
  376. "low_memory": True,
  377. "memory_map": False,
  378. "float_precision": None,
  379. }
  380. _fwf_defaults = {"colspecs": "infer", "infer_nrows": 100, "widths": None}
  381. _c_unsupported = {"skipfooter"}
  382. _python_unsupported = {"low_memory", "float_precision"}
  383. _pyarrow_unsupported = {
  384. "skipfooter",
  385. "float_precision",
  386. "chunksize",
  387. "comment",
  388. "nrows",
  389. "thousands",
  390. "memory_map",
  391. "dialect",
  392. "on_bad_lines",
  393. "delim_whitespace",
  394. "quoting",
  395. "lineterminator",
  396. "converters",
  397. "iterator",
  398. "dayfirst",
  399. "verbose",
  400. "skipinitialspace",
  401. "low_memory",
  402. }
  403. class _DeprecationConfig(NamedTuple):
  404. default_value: Any
  405. msg: str | None
  406. @overload
  407. def validate_integer(name, val: None, min_val: int = ...) -> None:
  408. ...
  409. @overload
  410. def validate_integer(name, val: float, min_val: int = ...) -> int:
  411. ...
  412. @overload
  413. def validate_integer(name, val: int | None, min_val: int = ...) -> int | None:
  414. ...
  415. def validate_integer(name, val: int | float | None, min_val: int = 0) -> int | None:
  416. """
  417. Checks whether the 'name' parameter for parsing is either
  418. an integer OR float that can SAFELY be cast to an integer
  419. without losing accuracy. Raises a ValueError if that is
  420. not the case.
  421. Parameters
  422. ----------
  423. name : str
  424. Parameter name (used for error reporting)
  425. val : int or float
  426. The value to check
  427. min_val : int
  428. Minimum allowed value (val < min_val will result in a ValueError)
  429. """
  430. if val is None:
  431. return val
  432. msg = f"'{name:s}' must be an integer >={min_val:d}"
  433. if is_float(val):
  434. if int(val) != val:
  435. raise ValueError(msg)
  436. val = int(val)
  437. elif not (is_integer(val) and val >= min_val):
  438. raise ValueError(msg)
  439. return int(val)
  440. def _validate_names(names: Sequence[Hashable] | None) -> None:
  441. """
  442. Raise ValueError if the `names` parameter contains duplicates or has an
  443. invalid data type.
  444. Parameters
  445. ----------
  446. names : array-like or None
  447. An array containing a list of the names used for the output DataFrame.
  448. Raises
  449. ------
  450. ValueError
  451. If names are not unique or are not ordered (e.g. set).
  452. """
  453. if names is not None:
  454. if len(names) != len(set(names)):
  455. raise ValueError("Duplicate names are not allowed.")
  456. if not (
  457. is_list_like(names, allow_sets=False) or isinstance(names, abc.KeysView)
  458. ):
  459. raise ValueError("Names should be an ordered collection.")
  460. def _read(
  461. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], kwds
  462. ) -> DataFrame | TextFileReader:
  463. """Generic reader of line files."""
  464. # if we pass a date_parser and parse_dates=False, we should not parse the
  465. # dates GH#44366
  466. if kwds.get("parse_dates", None) is None:
  467. if (
  468. kwds.get("date_parser", lib.no_default) is lib.no_default
  469. and kwds.get("date_format", None) is None
  470. ):
  471. kwds["parse_dates"] = False
  472. else:
  473. kwds["parse_dates"] = True
  474. # Extract some of the arguments (pass chunksize on).
  475. iterator = kwds.get("iterator", False)
  476. chunksize = kwds.get("chunksize", None)
  477. if kwds.get("engine") == "pyarrow":
  478. if iterator:
  479. raise ValueError(
  480. "The 'iterator' option is not supported with the 'pyarrow' engine"
  481. )
  482. if chunksize is not None:
  483. raise ValueError(
  484. "The 'chunksize' option is not supported with the 'pyarrow' engine"
  485. )
  486. else:
  487. chunksize = validate_integer("chunksize", chunksize, 1)
  488. nrows = kwds.get("nrows", None)
  489. # Check for duplicates in names.
  490. _validate_names(kwds.get("names", None))
  491. # Create the parser.
  492. parser = TextFileReader(filepath_or_buffer, **kwds)
  493. if chunksize or iterator:
  494. return parser
  495. with parser:
  496. return parser.read(nrows)
  497. # iterator=True -> TextFileReader
  498. @overload
  499. def read_csv(
  500. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  501. *,
  502. sep: str | None | lib.NoDefault = ...,
  503. delimiter: str | None | lib.NoDefault = ...,
  504. header: int | Sequence[int] | None | Literal["infer"] = ...,
  505. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  506. index_col: IndexLabel | Literal[False] | None = ...,
  507. usecols=...,
  508. dtype: DtypeArg | None = ...,
  509. engine: CSVEngine | None = ...,
  510. converters=...,
  511. true_values=...,
  512. false_values=...,
  513. skipinitialspace: bool = ...,
  514. skiprows=...,
  515. skipfooter: int = ...,
  516. nrows: int | None = ...,
  517. na_values=...,
  518. keep_default_na: bool = ...,
  519. na_filter: bool = ...,
  520. verbose: bool = ...,
  521. skip_blank_lines: bool = ...,
  522. parse_dates: bool | Sequence[Hashable] | None = ...,
  523. infer_datetime_format: bool | lib.NoDefault = ...,
  524. keep_date_col: bool = ...,
  525. date_parser=...,
  526. date_format: str | None = ...,
  527. dayfirst: bool = ...,
  528. cache_dates: bool = ...,
  529. iterator: Literal[True],
  530. chunksize: int | None = ...,
  531. compression: CompressionOptions = ...,
  532. thousands: str | None = ...,
  533. decimal: str = ...,
  534. lineterminator: str | None = ...,
  535. quotechar: str = ...,
  536. quoting: int = ...,
  537. doublequote: bool = ...,
  538. escapechar: str | None = ...,
  539. comment: str | None = ...,
  540. encoding: str | None = ...,
  541. encoding_errors: str | None = ...,
  542. dialect: str | csv.Dialect | None = ...,
  543. on_bad_lines=...,
  544. delim_whitespace: bool = ...,
  545. low_memory=...,
  546. memory_map: bool = ...,
  547. float_precision: Literal["high", "legacy"] | None = ...,
  548. storage_options: StorageOptions = ...,
  549. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  550. ) -> TextFileReader:
  551. ...
  552. # chunksize=int -> TextFileReader
  553. @overload
  554. def read_csv(
  555. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  556. *,
  557. sep: str | None | lib.NoDefault = ...,
  558. delimiter: str | None | lib.NoDefault = ...,
  559. header: int | Sequence[int] | None | Literal["infer"] = ...,
  560. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  561. index_col: IndexLabel | Literal[False] | None = ...,
  562. usecols=...,
  563. dtype: DtypeArg | None = ...,
  564. engine: CSVEngine | None = ...,
  565. converters=...,
  566. true_values=...,
  567. false_values=...,
  568. skipinitialspace: bool = ...,
  569. skiprows=...,
  570. skipfooter: int = ...,
  571. nrows: int | None = ...,
  572. na_values=...,
  573. keep_default_na: bool = ...,
  574. na_filter: bool = ...,
  575. verbose: bool = ...,
  576. skip_blank_lines: bool = ...,
  577. parse_dates: bool | Sequence[Hashable] | None = ...,
  578. infer_datetime_format: bool | lib.NoDefault = ...,
  579. keep_date_col: bool = ...,
  580. date_parser=...,
  581. date_format: str | None = ...,
  582. dayfirst: bool = ...,
  583. cache_dates: bool = ...,
  584. iterator: bool = ...,
  585. chunksize: int,
  586. compression: CompressionOptions = ...,
  587. thousands: str | None = ...,
  588. decimal: str = ...,
  589. lineterminator: str | None = ...,
  590. quotechar: str = ...,
  591. quoting: int = ...,
  592. doublequote: bool = ...,
  593. escapechar: str | None = ...,
  594. comment: str | None = ...,
  595. encoding: str | None = ...,
  596. encoding_errors: str | None = ...,
  597. dialect: str | csv.Dialect | None = ...,
  598. on_bad_lines=...,
  599. delim_whitespace: bool = ...,
  600. low_memory=...,
  601. memory_map: bool = ...,
  602. float_precision: Literal["high", "legacy"] | None = ...,
  603. storage_options: StorageOptions = ...,
  604. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  605. ) -> TextFileReader:
  606. ...
  607. # default case -> DataFrame
  608. @overload
  609. def read_csv(
  610. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  611. *,
  612. sep: str | None | lib.NoDefault = ...,
  613. delimiter: str | None | lib.NoDefault = ...,
  614. header: int | Sequence[int] | None | Literal["infer"] = ...,
  615. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  616. index_col: IndexLabel | Literal[False] | None = ...,
  617. usecols=...,
  618. dtype: DtypeArg | None = ...,
  619. engine: CSVEngine | None = ...,
  620. converters=...,
  621. true_values=...,
  622. false_values=...,
  623. skipinitialspace: bool = ...,
  624. skiprows=...,
  625. skipfooter: int = ...,
  626. nrows: int | None = ...,
  627. na_values=...,
  628. keep_default_na: bool = ...,
  629. na_filter: bool = ...,
  630. verbose: bool = ...,
  631. skip_blank_lines: bool = ...,
  632. parse_dates: bool | Sequence[Hashable] | None = ...,
  633. infer_datetime_format: bool | lib.NoDefault = ...,
  634. keep_date_col: bool = ...,
  635. date_parser=...,
  636. date_format: str | None = ...,
  637. dayfirst: bool = ...,
  638. cache_dates: bool = ...,
  639. iterator: Literal[False] = ...,
  640. chunksize: None = ...,
  641. compression: CompressionOptions = ...,
  642. thousands: str | None = ...,
  643. decimal: str = ...,
  644. lineterminator: str | None = ...,
  645. quotechar: str = ...,
  646. quoting: int = ...,
  647. doublequote: bool = ...,
  648. escapechar: str | None = ...,
  649. comment: str | None = ...,
  650. encoding: str | None = ...,
  651. encoding_errors: str | None = ...,
  652. dialect: str | csv.Dialect | None = ...,
  653. on_bad_lines=...,
  654. delim_whitespace: bool = ...,
  655. low_memory=...,
  656. memory_map: bool = ...,
  657. float_precision: Literal["high", "legacy"] | None = ...,
  658. storage_options: StorageOptions = ...,
  659. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  660. ) -> DataFrame:
  661. ...
  662. # Unions -> DataFrame | TextFileReader
  663. @overload
  664. def read_csv(
  665. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  666. *,
  667. sep: str | None | lib.NoDefault = ...,
  668. delimiter: str | None | lib.NoDefault = ...,
  669. header: int | Sequence[int] | None | Literal["infer"] = ...,
  670. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  671. index_col: IndexLabel | Literal[False] | None = ...,
  672. usecols=...,
  673. dtype: DtypeArg | None = ...,
  674. engine: CSVEngine | None = ...,
  675. converters=...,
  676. true_values=...,
  677. false_values=...,
  678. skipinitialspace: bool = ...,
  679. skiprows=...,
  680. skipfooter: int = ...,
  681. nrows: int | None = ...,
  682. na_values=...,
  683. keep_default_na: bool = ...,
  684. na_filter: bool = ...,
  685. verbose: bool = ...,
  686. skip_blank_lines: bool = ...,
  687. parse_dates: bool | Sequence[Hashable] | None = ...,
  688. infer_datetime_format: bool | lib.NoDefault = ...,
  689. keep_date_col: bool = ...,
  690. date_parser=...,
  691. date_format: str | None = ...,
  692. dayfirst: bool = ...,
  693. cache_dates: bool = ...,
  694. iterator: bool = ...,
  695. chunksize: int | None = ...,
  696. compression: CompressionOptions = ...,
  697. thousands: str | None = ...,
  698. decimal: str = ...,
  699. lineterminator: str | None = ...,
  700. quotechar: str = ...,
  701. quoting: int = ...,
  702. doublequote: bool = ...,
  703. escapechar: str | None = ...,
  704. comment: str | None = ...,
  705. encoding: str | None = ...,
  706. encoding_errors: str | None = ...,
  707. dialect: str | csv.Dialect | None = ...,
  708. on_bad_lines=...,
  709. delim_whitespace: bool = ...,
  710. low_memory=...,
  711. memory_map: bool = ...,
  712. float_precision: Literal["high", "legacy"] | None = ...,
  713. storage_options: StorageOptions = ...,
  714. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  715. ) -> DataFrame | TextFileReader:
  716. ...
  717. @Appender(
  718. _doc_read_csv_and_table.format(
  719. func_name="read_csv",
  720. summary="Read a comma-separated values (csv) file into DataFrame.",
  721. _default_sep="','",
  722. storage_options=_shared_docs["storage_options"],
  723. decompression_options=_shared_docs["decompression_options"]
  724. % "filepath_or_buffer",
  725. )
  726. )
  727. def read_csv(
  728. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  729. *,
  730. sep: str | None | lib.NoDefault = lib.no_default,
  731. delimiter: str | None | lib.NoDefault = None,
  732. # Column and Index Locations and Names
  733. header: int | Sequence[int] | None | Literal["infer"] = "infer",
  734. names: Sequence[Hashable] | None | lib.NoDefault = lib.no_default,
  735. index_col: IndexLabel | Literal[False] | None = None,
  736. usecols=None,
  737. # General Parsing Configuration
  738. dtype: DtypeArg | None = None,
  739. engine: CSVEngine | None = None,
  740. converters=None,
  741. true_values=None,
  742. false_values=None,
  743. skipinitialspace: bool = False,
  744. skiprows=None,
  745. skipfooter: int = 0,
  746. nrows: int | None = None,
  747. # NA and Missing Data Handling
  748. na_values=None,
  749. keep_default_na: bool = True,
  750. na_filter: bool = True,
  751. verbose: bool = False,
  752. skip_blank_lines: bool = True,
  753. # Datetime Handling
  754. parse_dates: bool | Sequence[Hashable] | None = None,
  755. infer_datetime_format: bool | lib.NoDefault = lib.no_default,
  756. keep_date_col: bool = False,
  757. date_parser=lib.no_default,
  758. date_format: str | None = None,
  759. dayfirst: bool = False,
  760. cache_dates: bool = True,
  761. # Iteration
  762. iterator: bool = False,
  763. chunksize: int | None = None,
  764. # Quoting, Compression, and File Format
  765. compression: CompressionOptions = "infer",
  766. thousands: str | None = None,
  767. decimal: str = ".",
  768. lineterminator: str | None = None,
  769. quotechar: str = '"',
  770. quoting: int = csv.QUOTE_MINIMAL,
  771. doublequote: bool = True,
  772. escapechar: str | None = None,
  773. comment: str | None = None,
  774. encoding: str | None = None,
  775. encoding_errors: str | None = "strict",
  776. dialect: str | csv.Dialect | None = None,
  777. # Error Handling
  778. on_bad_lines: str = "error",
  779. # Internal
  780. delim_whitespace: bool = False,
  781. low_memory=_c_parser_defaults["low_memory"],
  782. memory_map: bool = False,
  783. float_precision: Literal["high", "legacy"] | None = None,
  784. storage_options: StorageOptions = None,
  785. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  786. ) -> DataFrame | TextFileReader:
  787. if infer_datetime_format is not lib.no_default:
  788. warnings.warn(
  789. "The argument 'infer_datetime_format' is deprecated and will "
  790. "be removed in a future version. "
  791. "A strict version of it is now the default, see "
  792. "https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. "
  793. "You can safely remove this argument.",
  794. FutureWarning,
  795. stacklevel=find_stack_level(),
  796. )
  797. # locals() should never be modified
  798. kwds = locals().copy()
  799. del kwds["filepath_or_buffer"]
  800. del kwds["sep"]
  801. kwds_defaults = _refine_defaults_read(
  802. dialect,
  803. delimiter,
  804. delim_whitespace,
  805. engine,
  806. sep,
  807. on_bad_lines,
  808. names,
  809. defaults={"delimiter": ","},
  810. dtype_backend=dtype_backend,
  811. )
  812. kwds.update(kwds_defaults)
  813. return _read(filepath_or_buffer, kwds)
  814. # iterator=True -> TextFileReader
  815. @overload
  816. def read_table(
  817. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  818. *,
  819. sep: str | None | lib.NoDefault = ...,
  820. delimiter: str | None | lib.NoDefault = ...,
  821. header: int | Sequence[int] | None | Literal["infer"] = ...,
  822. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  823. index_col: IndexLabel | Literal[False] | None = ...,
  824. usecols=...,
  825. dtype: DtypeArg | None = ...,
  826. engine: CSVEngine | None = ...,
  827. converters=...,
  828. true_values=...,
  829. false_values=...,
  830. skipinitialspace: bool = ...,
  831. skiprows=...,
  832. skipfooter: int = ...,
  833. nrows: int | None = ...,
  834. na_values=...,
  835. keep_default_na: bool = ...,
  836. na_filter: bool = ...,
  837. verbose: bool = ...,
  838. skip_blank_lines: bool = ...,
  839. parse_dates: bool | Sequence[Hashable] = ...,
  840. infer_datetime_format: bool | lib.NoDefault = ...,
  841. keep_date_col: bool = ...,
  842. date_parser=...,
  843. date_format: str | None = ...,
  844. dayfirst: bool = ...,
  845. cache_dates: bool = ...,
  846. iterator: Literal[True],
  847. chunksize: int | None = ...,
  848. compression: CompressionOptions = ...,
  849. thousands: str | None = ...,
  850. decimal: str = ...,
  851. lineterminator: str | None = ...,
  852. quotechar: str = ...,
  853. quoting: int = ...,
  854. doublequote: bool = ...,
  855. escapechar: str | None = ...,
  856. comment: str | None = ...,
  857. encoding: str | None = ...,
  858. encoding_errors: str | None = ...,
  859. dialect: str | csv.Dialect | None = ...,
  860. on_bad_lines=...,
  861. delim_whitespace: bool = ...,
  862. low_memory=...,
  863. memory_map: bool = ...,
  864. float_precision: str | None = ...,
  865. storage_options: StorageOptions = ...,
  866. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  867. ) -> TextFileReader:
  868. ...
  869. # chunksize=int -> TextFileReader
  870. @overload
  871. def read_table(
  872. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  873. *,
  874. sep: str | None | lib.NoDefault = ...,
  875. delimiter: str | None | lib.NoDefault = ...,
  876. header: int | Sequence[int] | None | Literal["infer"] = ...,
  877. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  878. index_col: IndexLabel | Literal[False] | None = ...,
  879. usecols=...,
  880. dtype: DtypeArg | None = ...,
  881. engine: CSVEngine | None = ...,
  882. converters=...,
  883. true_values=...,
  884. false_values=...,
  885. skipinitialspace: bool = ...,
  886. skiprows=...,
  887. skipfooter: int = ...,
  888. nrows: int | None = ...,
  889. na_values=...,
  890. keep_default_na: bool = ...,
  891. na_filter: bool = ...,
  892. verbose: bool = ...,
  893. skip_blank_lines: bool = ...,
  894. parse_dates: bool | Sequence[Hashable] = ...,
  895. infer_datetime_format: bool | lib.NoDefault = ...,
  896. keep_date_col: bool = ...,
  897. date_parser=...,
  898. date_format: str | None = ...,
  899. dayfirst: bool = ...,
  900. cache_dates: bool = ...,
  901. iterator: bool = ...,
  902. chunksize: int,
  903. compression: CompressionOptions = ...,
  904. thousands: str | None = ...,
  905. decimal: str = ...,
  906. lineterminator: str | None = ...,
  907. quotechar: str = ...,
  908. quoting: int = ...,
  909. doublequote: bool = ...,
  910. escapechar: str | None = ...,
  911. comment: str | None = ...,
  912. encoding: str | None = ...,
  913. encoding_errors: str | None = ...,
  914. dialect: str | csv.Dialect | None = ...,
  915. on_bad_lines=...,
  916. delim_whitespace: bool = ...,
  917. low_memory=...,
  918. memory_map: bool = ...,
  919. float_precision: str | None = ...,
  920. storage_options: StorageOptions = ...,
  921. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  922. ) -> TextFileReader:
  923. ...
  924. # default -> DataFrame
  925. @overload
  926. def read_table(
  927. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  928. *,
  929. sep: str | None | lib.NoDefault = ...,
  930. delimiter: str | None | lib.NoDefault = ...,
  931. header: int | Sequence[int] | None | Literal["infer"] = ...,
  932. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  933. index_col: IndexLabel | Literal[False] | None = ...,
  934. usecols=...,
  935. dtype: DtypeArg | None = ...,
  936. engine: CSVEngine | None = ...,
  937. converters=...,
  938. true_values=...,
  939. false_values=...,
  940. skipinitialspace: bool = ...,
  941. skiprows=...,
  942. skipfooter: int = ...,
  943. nrows: int | None = ...,
  944. na_values=...,
  945. keep_default_na: bool = ...,
  946. na_filter: bool = ...,
  947. verbose: bool = ...,
  948. skip_blank_lines: bool = ...,
  949. parse_dates: bool | Sequence[Hashable] = ...,
  950. infer_datetime_format: bool | lib.NoDefault = ...,
  951. keep_date_col: bool = ...,
  952. date_parser=...,
  953. date_format: str | None = ...,
  954. dayfirst: bool = ...,
  955. cache_dates: bool = ...,
  956. iterator: Literal[False] = ...,
  957. chunksize: None = ...,
  958. compression: CompressionOptions = ...,
  959. thousands: str | None = ...,
  960. decimal: str = ...,
  961. lineterminator: str | None = ...,
  962. quotechar: str = ...,
  963. quoting: int = ...,
  964. doublequote: bool = ...,
  965. escapechar: str | None = ...,
  966. comment: str | None = ...,
  967. encoding: str | None = ...,
  968. encoding_errors: str | None = ...,
  969. dialect: str | csv.Dialect | None = ...,
  970. on_bad_lines=...,
  971. delim_whitespace: bool = ...,
  972. low_memory=...,
  973. memory_map: bool = ...,
  974. float_precision: str | None = ...,
  975. storage_options: StorageOptions = ...,
  976. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  977. ) -> DataFrame:
  978. ...
  979. # Unions -> DataFrame | TextFileReader
  980. @overload
  981. def read_table(
  982. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  983. *,
  984. sep: str | None | lib.NoDefault = ...,
  985. delimiter: str | None | lib.NoDefault = ...,
  986. header: int | Sequence[int] | None | Literal["infer"] = ...,
  987. names: Sequence[Hashable] | None | lib.NoDefault = ...,
  988. index_col: IndexLabel | Literal[False] | None = ...,
  989. usecols=...,
  990. dtype: DtypeArg | None = ...,
  991. engine: CSVEngine | None = ...,
  992. converters=...,
  993. true_values=...,
  994. false_values=...,
  995. skipinitialspace: bool = ...,
  996. skiprows=...,
  997. skipfooter: int = ...,
  998. nrows: int | None = ...,
  999. na_values=...,
  1000. keep_default_na: bool = ...,
  1001. na_filter: bool = ...,
  1002. verbose: bool = ...,
  1003. skip_blank_lines: bool = ...,
  1004. parse_dates: bool | Sequence[Hashable] = ...,
  1005. infer_datetime_format: bool | lib.NoDefault = ...,
  1006. keep_date_col: bool = ...,
  1007. date_parser=...,
  1008. date_format: str | None = ...,
  1009. dayfirst: bool = ...,
  1010. cache_dates: bool = ...,
  1011. iterator: bool = ...,
  1012. chunksize: int | None = ...,
  1013. compression: CompressionOptions = ...,
  1014. thousands: str | None = ...,
  1015. decimal: str = ...,
  1016. lineterminator: str | None = ...,
  1017. quotechar: str = ...,
  1018. quoting: int = ...,
  1019. doublequote: bool = ...,
  1020. escapechar: str | None = ...,
  1021. comment: str | None = ...,
  1022. encoding: str | None = ...,
  1023. encoding_errors: str | None = ...,
  1024. dialect: str | csv.Dialect | None = ...,
  1025. on_bad_lines=...,
  1026. delim_whitespace: bool = ...,
  1027. low_memory=...,
  1028. memory_map: bool = ...,
  1029. float_precision: str | None = ...,
  1030. storage_options: StorageOptions = ...,
  1031. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  1032. ) -> DataFrame | TextFileReader:
  1033. ...
  1034. @Appender(
  1035. _doc_read_csv_and_table.format(
  1036. func_name="read_table",
  1037. summary="Read general delimited file into DataFrame.",
  1038. _default_sep=r"'\\t' (tab-stop)",
  1039. storage_options=_shared_docs["storage_options"],
  1040. decompression_options=_shared_docs["decompression_options"]
  1041. % "filepath_or_buffer",
  1042. )
  1043. )
  1044. def read_table(
  1045. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  1046. *,
  1047. sep: str | None | lib.NoDefault = lib.no_default,
  1048. delimiter: str | None | lib.NoDefault = None,
  1049. # Column and Index Locations and Names
  1050. header: int | Sequence[int] | None | Literal["infer"] = "infer",
  1051. names: Sequence[Hashable] | None | lib.NoDefault = lib.no_default,
  1052. index_col: IndexLabel | Literal[False] | None = None,
  1053. usecols=None,
  1054. # General Parsing Configuration
  1055. dtype: DtypeArg | None = None,
  1056. engine: CSVEngine | None = None,
  1057. converters=None,
  1058. true_values=None,
  1059. false_values=None,
  1060. skipinitialspace: bool = False,
  1061. skiprows=None,
  1062. skipfooter: int = 0,
  1063. nrows: int | None = None,
  1064. # NA and Missing Data Handling
  1065. na_values=None,
  1066. keep_default_na: bool = True,
  1067. na_filter: bool = True,
  1068. verbose: bool = False,
  1069. skip_blank_lines: bool = True,
  1070. # Datetime Handling
  1071. parse_dates: bool | Sequence[Hashable] = False,
  1072. infer_datetime_format: bool | lib.NoDefault = lib.no_default,
  1073. keep_date_col: bool = False,
  1074. date_parser=lib.no_default,
  1075. date_format: str | None = None,
  1076. dayfirst: bool = False,
  1077. cache_dates: bool = True,
  1078. # Iteration
  1079. iterator: bool = False,
  1080. chunksize: int | None = None,
  1081. # Quoting, Compression, and File Format
  1082. compression: CompressionOptions = "infer",
  1083. thousands: str | None = None,
  1084. decimal: str = ".",
  1085. lineterminator: str | None = None,
  1086. quotechar: str = '"',
  1087. quoting: int = csv.QUOTE_MINIMAL,
  1088. doublequote: bool = True,
  1089. escapechar: str | None = None,
  1090. comment: str | None = None,
  1091. encoding: str | None = None,
  1092. encoding_errors: str | None = "strict",
  1093. dialect: str | csv.Dialect | None = None,
  1094. # Error Handling
  1095. on_bad_lines: str = "error",
  1096. # Internal
  1097. delim_whitespace: bool = False,
  1098. low_memory=_c_parser_defaults["low_memory"],
  1099. memory_map: bool = False,
  1100. float_precision: str | None = None,
  1101. storage_options: StorageOptions = None,
  1102. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  1103. ) -> DataFrame | TextFileReader:
  1104. if infer_datetime_format is not lib.no_default:
  1105. warnings.warn(
  1106. "The argument 'infer_datetime_format' is deprecated and will "
  1107. "be removed in a future version. "
  1108. "A strict version of it is now the default, see "
  1109. "https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. "
  1110. "You can safely remove this argument.",
  1111. FutureWarning,
  1112. stacklevel=find_stack_level(),
  1113. )
  1114. # locals() should never be modified
  1115. kwds = locals().copy()
  1116. del kwds["filepath_or_buffer"]
  1117. del kwds["sep"]
  1118. kwds_defaults = _refine_defaults_read(
  1119. dialect,
  1120. delimiter,
  1121. delim_whitespace,
  1122. engine,
  1123. sep,
  1124. on_bad_lines,
  1125. names,
  1126. defaults={"delimiter": "\t"},
  1127. dtype_backend=dtype_backend,
  1128. )
  1129. kwds.update(kwds_defaults)
  1130. return _read(filepath_or_buffer, kwds)
  1131. def read_fwf(
  1132. filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
  1133. *,
  1134. colspecs: Sequence[tuple[int, int]] | str | None = "infer",
  1135. widths: Sequence[int] | None = None,
  1136. infer_nrows: int = 100,
  1137. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  1138. **kwds,
  1139. ) -> DataFrame | TextFileReader:
  1140. r"""
  1141. Read a table of fixed-width formatted lines into DataFrame.
  1142. Also supports optionally iterating or breaking of the file
  1143. into chunks.
  1144. Additional help can be found in the `online docs for IO Tools
  1145. <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.
  1146. Parameters
  1147. ----------
  1148. filepath_or_buffer : str, path object, or file-like object
  1149. String, path object (implementing ``os.PathLike[str]``), or file-like
  1150. object implementing a text ``read()`` function.The string could be a URL.
  1151. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is
  1152. expected. A local file could be:
  1153. ``file://localhost/path/to/table.csv``.
  1154. colspecs : list of tuple (int, int) or 'infer'. optional
  1155. A list of tuples giving the extents of the fixed-width
  1156. fields of each line as half-open intervals (i.e., [from, to[ ).
  1157. String value 'infer' can be used to instruct the parser to try
  1158. detecting the column specifications from the first 100 rows of
  1159. the data which are not being skipped via skiprows (default='infer').
  1160. widths : list of int, optional
  1161. A list of field widths which can be used instead of 'colspecs' if
  1162. the intervals are contiguous.
  1163. infer_nrows : int, default 100
  1164. The number of rows to consider when letting the parser determine the
  1165. `colspecs`.
  1166. dtype_backend : {"numpy_nullable", "pyarrow"}, defaults to NumPy backed DataFrames
  1167. Which dtype_backend to use, e.g. whether a DataFrame should have NumPy
  1168. arrays, nullable dtypes are used for all dtypes that have a nullable
  1169. implementation when "numpy_nullable" is set, pyarrow is used for all
  1170. dtypes if "pyarrow" is set.
  1171. The dtype_backends are still experimential.
  1172. .. versionadded:: 2.0
  1173. **kwds : optional
  1174. Optional keyword arguments can be passed to ``TextFileReader``.
  1175. Returns
  1176. -------
  1177. DataFrame or TextFileReader
  1178. A comma-separated values (csv) file is returned as two-dimensional
  1179. data structure with labeled axes.
  1180. See Also
  1181. --------
  1182. DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
  1183. read_csv : Read a comma-separated values (csv) file into DataFrame.
  1184. Examples
  1185. --------
  1186. >>> pd.read_fwf('data.csv') # doctest: +SKIP
  1187. """
  1188. # Check input arguments.
  1189. if colspecs is None and widths is None:
  1190. raise ValueError("Must specify either colspecs or widths")
  1191. if colspecs not in (None, "infer") and widths is not None:
  1192. raise ValueError("You must specify only one of 'widths' and 'colspecs'")
  1193. # Compute 'colspecs' from 'widths', if specified.
  1194. if widths is not None:
  1195. colspecs, col = [], 0
  1196. for w in widths:
  1197. colspecs.append((col, col + w))
  1198. col += w
  1199. # for mypy
  1200. assert colspecs is not None
  1201. # GH#40830
  1202. # Ensure length of `colspecs` matches length of `names`
  1203. names = kwds.get("names")
  1204. if names is not None:
  1205. if len(names) != len(colspecs) and colspecs != "infer":
  1206. # need to check len(index_col) as it might contain
  1207. # unnamed indices, in which case it's name is not required
  1208. len_index = 0
  1209. if kwds.get("index_col") is not None:
  1210. index_col: Any = kwds.get("index_col")
  1211. if index_col is not False:
  1212. if not is_list_like(index_col):
  1213. len_index = 1
  1214. else:
  1215. len_index = len(index_col)
  1216. if kwds.get("usecols") is None and len(names) + len_index != len(colspecs):
  1217. # If usecols is used colspec may be longer than names
  1218. raise ValueError("Length of colspecs must match length of names")
  1219. kwds["colspecs"] = colspecs
  1220. kwds["infer_nrows"] = infer_nrows
  1221. kwds["engine"] = "python-fwf"
  1222. check_dtype_backend(dtype_backend)
  1223. kwds["dtype_backend"] = dtype_backend
  1224. return _read(filepath_or_buffer, kwds)
  1225. class TextFileReader(abc.Iterator):
  1226. """
  1227. Passed dialect overrides any of the related parser options
  1228. """
  1229. def __init__(
  1230. self,
  1231. f: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str] | list,
  1232. engine: CSVEngine | None = None,
  1233. **kwds,
  1234. ) -> None:
  1235. if engine is not None:
  1236. engine_specified = True
  1237. else:
  1238. engine = "python"
  1239. engine_specified = False
  1240. self.engine = engine
  1241. self._engine_specified = kwds.get("engine_specified", engine_specified)
  1242. _validate_skipfooter(kwds)
  1243. dialect = _extract_dialect(kwds)
  1244. if dialect is not None:
  1245. if engine == "pyarrow":
  1246. raise ValueError(
  1247. "The 'dialect' option is not supported with the 'pyarrow' engine"
  1248. )
  1249. kwds = _merge_with_dialect_properties(dialect, kwds)
  1250. if kwds.get("header", "infer") == "infer":
  1251. kwds["header"] = 0 if kwds.get("names") is None else None
  1252. self.orig_options = kwds
  1253. # miscellanea
  1254. self._currow = 0
  1255. options = self._get_options_with_defaults(engine)
  1256. options["storage_options"] = kwds.get("storage_options", None)
  1257. self.chunksize = options.pop("chunksize", None)
  1258. self.nrows = options.pop("nrows", None)
  1259. self._check_file_or_buffer(f, engine)
  1260. self.options, self.engine = self._clean_options(options, engine)
  1261. if "has_index_names" in kwds:
  1262. self.options["has_index_names"] = kwds["has_index_names"]
  1263. self.handles: IOHandles | None = None
  1264. self._engine = self._make_engine(f, self.engine)
  1265. def close(self) -> None:
  1266. if self.handles is not None:
  1267. self.handles.close()
  1268. self._engine.close()
  1269. def _get_options_with_defaults(self, engine: CSVEngine) -> dict[str, Any]:
  1270. kwds = self.orig_options
  1271. options = {}
  1272. default: object | None
  1273. for argname, default in parser_defaults.items():
  1274. value = kwds.get(argname, default)
  1275. # see gh-12935
  1276. if (
  1277. engine == "pyarrow"
  1278. and argname in _pyarrow_unsupported
  1279. and value != default
  1280. and value != getattr(value, "value", default)
  1281. ):
  1282. raise ValueError(
  1283. f"The {repr(argname)} option is not supported with the "
  1284. f"'pyarrow' engine"
  1285. )
  1286. options[argname] = value
  1287. for argname, default in _c_parser_defaults.items():
  1288. if argname in kwds:
  1289. value = kwds[argname]
  1290. if engine != "c" and value != default:
  1291. if "python" in engine and argname not in _python_unsupported:
  1292. pass
  1293. else:
  1294. raise ValueError(
  1295. f"The {repr(argname)} option is not supported with the "
  1296. f"{repr(engine)} engine"
  1297. )
  1298. else:
  1299. value = default
  1300. options[argname] = value
  1301. if engine == "python-fwf":
  1302. for argname, default in _fwf_defaults.items():
  1303. options[argname] = kwds.get(argname, default)
  1304. return options
  1305. def _check_file_or_buffer(self, f, engine: CSVEngine) -> None:
  1306. # see gh-16530
  1307. if is_file_like(f) and engine != "c" and not hasattr(f, "__iter__"):
  1308. # The C engine doesn't need the file-like to have the "__iter__"
  1309. # attribute. However, the Python engine needs "__iter__(...)"
  1310. # when iterating through such an object, meaning it
  1311. # needs to have that attribute
  1312. raise ValueError(
  1313. "The 'python' engine cannot iterate through this file buffer."
  1314. )
  1315. def _clean_options(
  1316. self, options: dict[str, Any], engine: CSVEngine
  1317. ) -> tuple[dict[str, Any], CSVEngine]:
  1318. result = options.copy()
  1319. fallback_reason = None
  1320. # C engine not supported yet
  1321. if engine == "c":
  1322. if options["skipfooter"] > 0:
  1323. fallback_reason = "the 'c' engine does not support skipfooter"
  1324. engine = "python"
  1325. sep = options["delimiter"]
  1326. delim_whitespace = options["delim_whitespace"]
  1327. if sep is None and not delim_whitespace:
  1328. if engine in ("c", "pyarrow"):
  1329. fallback_reason = (
  1330. f"the '{engine}' engine does not support "
  1331. "sep=None with delim_whitespace=False"
  1332. )
  1333. engine = "python"
  1334. elif sep is not None and len(sep) > 1:
  1335. if engine == "c" and sep == r"\s+":
  1336. result["delim_whitespace"] = True
  1337. del result["delimiter"]
  1338. elif engine not in ("python", "python-fwf"):
  1339. # wait until regex engine integrated
  1340. fallback_reason = (
  1341. f"the '{engine}' engine does not support "
  1342. "regex separators (separators > 1 char and "
  1343. r"different from '\s+' are interpreted as regex)"
  1344. )
  1345. engine = "python"
  1346. elif delim_whitespace:
  1347. if "python" in engine:
  1348. result["delimiter"] = r"\s+"
  1349. elif sep is not None:
  1350. encodeable = True
  1351. encoding = sys.getfilesystemencoding() or "utf-8"
  1352. try:
  1353. if len(sep.encode(encoding)) > 1:
  1354. encodeable = False
  1355. except UnicodeDecodeError:
  1356. encodeable = False
  1357. if not encodeable and engine not in ("python", "python-fwf"):
  1358. fallback_reason = (
  1359. f"the separator encoded in {encoding} "
  1360. f"is > 1 char long, and the '{engine}' engine "
  1361. "does not support such separators"
  1362. )
  1363. engine = "python"
  1364. quotechar = options["quotechar"]
  1365. if quotechar is not None and isinstance(quotechar, (str, bytes)):
  1366. if (
  1367. len(quotechar) == 1
  1368. and ord(quotechar) > 127
  1369. and engine not in ("python", "python-fwf")
  1370. ):
  1371. fallback_reason = (
  1372. "ord(quotechar) > 127, meaning the "
  1373. "quotechar is larger than one byte, "
  1374. f"and the '{engine}' engine does not support such quotechars"
  1375. )
  1376. engine = "python"
  1377. if fallback_reason and self._engine_specified:
  1378. raise ValueError(fallback_reason)
  1379. if engine == "c":
  1380. for arg in _c_unsupported:
  1381. del result[arg]
  1382. if "python" in engine:
  1383. for arg in _python_unsupported:
  1384. if fallback_reason and result[arg] != _c_parser_defaults[arg]:
  1385. raise ValueError(
  1386. "Falling back to the 'python' engine because "
  1387. f"{fallback_reason}, but this causes {repr(arg)} to be "
  1388. "ignored as it is not supported by the 'python' engine."
  1389. )
  1390. del result[arg]
  1391. if fallback_reason:
  1392. warnings.warn(
  1393. (
  1394. "Falling back to the 'python' engine because "
  1395. f"{fallback_reason}; you can avoid this warning by specifying "
  1396. "engine='python'."
  1397. ),
  1398. ParserWarning,
  1399. stacklevel=find_stack_level(),
  1400. )
  1401. index_col = options["index_col"]
  1402. names = options["names"]
  1403. converters = options["converters"]
  1404. na_values = options["na_values"]
  1405. skiprows = options["skiprows"]
  1406. validate_header_arg(options["header"])
  1407. if index_col is True:
  1408. raise ValueError("The value of index_col couldn't be 'True'")
  1409. if is_index_col(index_col):
  1410. if not isinstance(index_col, (list, tuple, np.ndarray)):
  1411. index_col = [index_col]
  1412. result["index_col"] = index_col
  1413. names = list(names) if names is not None else names
  1414. # type conversion-related
  1415. if converters is not None:
  1416. if not isinstance(converters, dict):
  1417. raise TypeError(
  1418. "Type converters must be a dict or subclass, "
  1419. f"input was a {type(converters).__name__}"
  1420. )
  1421. else:
  1422. converters = {}
  1423. # Converting values to NA
  1424. keep_default_na = options["keep_default_na"]
  1425. na_values, na_fvalues = _clean_na_values(na_values, keep_default_na)
  1426. # handle skiprows; this is internally handled by the
  1427. # c-engine, so only need for python and pyarrow parsers
  1428. if engine == "pyarrow":
  1429. if not is_integer(skiprows) and skiprows is not None:
  1430. # pyarrow expects skiprows to be passed as an integer
  1431. raise ValueError(
  1432. "skiprows argument must be an integer when using "
  1433. "engine='pyarrow'"
  1434. )
  1435. else:
  1436. if is_integer(skiprows):
  1437. skiprows = list(range(skiprows))
  1438. if skiprows is None:
  1439. skiprows = set()
  1440. elif not callable(skiprows):
  1441. skiprows = set(skiprows)
  1442. # put stuff back
  1443. result["names"] = names
  1444. result["converters"] = converters
  1445. result["na_values"] = na_values
  1446. result["na_fvalues"] = na_fvalues
  1447. result["skiprows"] = skiprows
  1448. return result, engine
  1449. def __next__(self) -> DataFrame:
  1450. try:
  1451. return self.get_chunk()
  1452. except StopIteration:
  1453. self.close()
  1454. raise
  1455. def _make_engine(
  1456. self,
  1457. f: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str] | list | IO,
  1458. engine: CSVEngine = "c",
  1459. ) -> ParserBase:
  1460. mapping: dict[str, type[ParserBase]] = {
  1461. "c": CParserWrapper,
  1462. "python": PythonParser,
  1463. "pyarrow": ArrowParserWrapper,
  1464. "python-fwf": FixedWidthFieldParser,
  1465. }
  1466. if engine not in mapping:
  1467. raise ValueError(
  1468. f"Unknown engine: {engine} (valid options are {mapping.keys()})"
  1469. )
  1470. if not isinstance(f, list):
  1471. # open file here
  1472. is_text = True
  1473. mode = "r"
  1474. if engine == "pyarrow":
  1475. is_text = False
  1476. mode = "rb"
  1477. elif (
  1478. engine == "c"
  1479. and self.options.get("encoding", "utf-8") == "utf-8"
  1480. and isinstance(stringify_path(f), str)
  1481. ):
  1482. # c engine can decode utf-8 bytes, adding TextIOWrapper makes
  1483. # the c-engine especially for memory_map=True far slower
  1484. is_text = False
  1485. if "b" not in mode:
  1486. mode += "b"
  1487. self.handles = get_handle(
  1488. f,
  1489. mode,
  1490. encoding=self.options.get("encoding", None),
  1491. compression=self.options.get("compression", None),
  1492. memory_map=self.options.get("memory_map", False),
  1493. is_text=is_text,
  1494. errors=self.options.get("encoding_errors", "strict"),
  1495. storage_options=self.options.get("storage_options", None),
  1496. )
  1497. assert self.handles is not None
  1498. f = self.handles.handle
  1499. elif engine != "python":
  1500. msg = f"Invalid file path or buffer object type: {type(f)}"
  1501. raise ValueError(msg)
  1502. try:
  1503. return mapping[engine](f, **self.options)
  1504. except Exception:
  1505. if self.handles is not None:
  1506. self.handles.close()
  1507. raise
  1508. def _failover_to_python(self) -> None:
  1509. raise AbstractMethodError(self)
  1510. def read(self, nrows: int | None = None) -> DataFrame:
  1511. if self.engine == "pyarrow":
  1512. try:
  1513. # error: "ParserBase" has no attribute "read"
  1514. df = self._engine.read() # type: ignore[attr-defined]
  1515. except Exception:
  1516. self.close()
  1517. raise
  1518. else:
  1519. nrows = validate_integer("nrows", nrows)
  1520. try:
  1521. # error: "ParserBase" has no attribute "read"
  1522. (
  1523. index,
  1524. columns,
  1525. col_dict,
  1526. ) = self._engine.read( # type: ignore[attr-defined]
  1527. nrows
  1528. )
  1529. except Exception:
  1530. self.close()
  1531. raise
  1532. if index is None:
  1533. if col_dict:
  1534. # Any column is actually fine:
  1535. new_rows = len(next(iter(col_dict.values())))
  1536. index = RangeIndex(self._currow, self._currow + new_rows)
  1537. else:
  1538. new_rows = 0
  1539. else:
  1540. new_rows = len(index)
  1541. df = DataFrame(col_dict, columns=columns, index=index)
  1542. self._currow += new_rows
  1543. return df
  1544. def get_chunk(self, size: int | None = None) -> DataFrame:
  1545. if size is None:
  1546. size = self.chunksize
  1547. if self.nrows is not None:
  1548. if self._currow >= self.nrows:
  1549. raise StopIteration
  1550. size = min(size, self.nrows - self._currow)
  1551. return self.read(nrows=size)
  1552. def __enter__(self) -> TextFileReader:
  1553. return self
  1554. def __exit__(
  1555. self,
  1556. exc_type: type[BaseException] | None,
  1557. exc_value: BaseException | None,
  1558. traceback: TracebackType | None,
  1559. ) -> None:
  1560. self.close()
  1561. def TextParser(*args, **kwds) -> TextFileReader:
  1562. """
  1563. Converts lists of lists/tuples into DataFrames with proper type inference
  1564. and optional (e.g. string to datetime) conversion. Also enables iterating
  1565. lazily over chunks of large files
  1566. Parameters
  1567. ----------
  1568. data : file-like object or list
  1569. delimiter : separator character to use
  1570. dialect : str or csv.Dialect instance, optional
  1571. Ignored if delimiter is longer than 1 character
  1572. names : sequence, default
  1573. header : int, default 0
  1574. Row to use to parse column labels. Defaults to the first row. Prior
  1575. rows will be discarded
  1576. index_col : int or list, optional
  1577. Column or columns to use as the (possibly hierarchical) index
  1578. has_index_names: bool, default False
  1579. True if the cols defined in index_col have an index name and are
  1580. not in the header.
  1581. na_values : scalar, str, list-like, or dict, optional
  1582. Additional strings to recognize as NA/NaN.
  1583. keep_default_na : bool, default True
  1584. thousands : str, optional
  1585. Thousands separator
  1586. comment : str, optional
  1587. Comment out remainder of line
  1588. parse_dates : bool, default False
  1589. keep_date_col : bool, default False
  1590. date_parser : function, optional
  1591. .. deprecated:: 2.0.0
  1592. date_format : str or dict of column -> format, default ``None``
  1593. .. versionadded:: 2.0.0
  1594. skiprows : list of integers
  1595. Row numbers to skip
  1596. skipfooter : int
  1597. Number of line at bottom of file to skip
  1598. converters : dict, optional
  1599. Dict of functions for converting values in certain columns. Keys can
  1600. either be integers or column labels, values are functions that take one
  1601. input argument, the cell (not column) content, and return the
  1602. transformed content.
  1603. encoding : str, optional
  1604. Encoding to use for UTF when reading/writing (ex. 'utf-8')
  1605. float_precision : str, optional
  1606. Specifies which converter the C engine should use for floating-point
  1607. values. The options are `None` or `high` for the ordinary converter,
  1608. `legacy` for the original lower precision pandas converter, and
  1609. `round_trip` for the round-trip converter.
  1610. .. versionchanged:: 1.2
  1611. """
  1612. kwds["engine"] = "python"
  1613. return TextFileReader(*args, **kwds)
  1614. def _clean_na_values(na_values, keep_default_na: bool = True):
  1615. na_fvalues: set | dict
  1616. if na_values is None:
  1617. if keep_default_na:
  1618. na_values = STR_NA_VALUES
  1619. else:
  1620. na_values = set()
  1621. na_fvalues = set()
  1622. elif isinstance(na_values, dict):
  1623. old_na_values = na_values.copy()
  1624. na_values = {} # Prevent aliasing.
  1625. # Convert the values in the na_values dictionary
  1626. # into array-likes for further use. This is also
  1627. # where we append the default NaN values, provided
  1628. # that `keep_default_na=True`.
  1629. for k, v in old_na_values.items():
  1630. if not is_list_like(v):
  1631. v = [v]
  1632. if keep_default_na:
  1633. v = set(v) | STR_NA_VALUES
  1634. na_values[k] = v
  1635. na_fvalues = {k: _floatify_na_values(v) for k, v in na_values.items()}
  1636. else:
  1637. if not is_list_like(na_values):
  1638. na_values = [na_values]
  1639. na_values = _stringify_na_values(na_values)
  1640. if keep_default_na:
  1641. na_values = na_values | STR_NA_VALUES
  1642. na_fvalues = _floatify_na_values(na_values)
  1643. return na_values, na_fvalues
  1644. def _floatify_na_values(na_values):
  1645. # create float versions of the na_values
  1646. result = set()
  1647. for v in na_values:
  1648. try:
  1649. v = float(v)
  1650. if not np.isnan(v):
  1651. result.add(v)
  1652. except (TypeError, ValueError, OverflowError):
  1653. pass
  1654. return result
  1655. def _stringify_na_values(na_values):
  1656. """return a stringified and numeric for these values"""
  1657. result: list[str | float] = []
  1658. for x in na_values:
  1659. result.append(str(x))
  1660. result.append(x)
  1661. try:
  1662. v = float(x)
  1663. # we are like 999 here
  1664. if v == int(v):
  1665. v = int(v)
  1666. result.append(f"{v}.0")
  1667. result.append(str(v))
  1668. result.append(v)
  1669. except (TypeError, ValueError, OverflowError):
  1670. pass
  1671. try:
  1672. result.append(int(x))
  1673. except (TypeError, ValueError, OverflowError):
  1674. pass
  1675. return set(result)
  1676. def _refine_defaults_read(
  1677. dialect: str | csv.Dialect | None,
  1678. delimiter: str | None | lib.NoDefault,
  1679. delim_whitespace: bool,
  1680. engine: CSVEngine | None,
  1681. sep: str | None | lib.NoDefault,
  1682. on_bad_lines: str | Callable,
  1683. names: Sequence[Hashable] | None | lib.NoDefault,
  1684. defaults: dict[str, Any],
  1685. dtype_backend: DtypeBackend | lib.NoDefault,
  1686. ):
  1687. """Validate/refine default values of input parameters of read_csv, read_table.
  1688. Parameters
  1689. ----------
  1690. dialect : str or csv.Dialect
  1691. If provided, this parameter will override values (default or not) for the
  1692. following parameters: `delimiter`, `doublequote`, `escapechar`,
  1693. `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to
  1694. override values, a ParserWarning will be issued. See csv.Dialect
  1695. documentation for more details.
  1696. delimiter : str or object
  1697. Alias for sep.
  1698. delim_whitespace : bool
  1699. Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be
  1700. used as the sep. Equivalent to setting ``sep='\\s+'``. If this option
  1701. is set to True, nothing should be passed in for the ``delimiter``
  1702. parameter.
  1703. engine : {{'c', 'python'}}
  1704. Parser engine to use. The C engine is faster while the python engine is
  1705. currently more feature-complete.
  1706. sep : str or object
  1707. A delimiter provided by the user (str) or a sentinel value, i.e.
  1708. pandas._libs.lib.no_default.
  1709. on_bad_lines : str, callable
  1710. An option for handling bad lines or a sentinel value(None).
  1711. names : array-like, optional
  1712. List of column names to use. If the file contains a header row,
  1713. then you should explicitly pass ``header=0`` to override the column names.
  1714. Duplicates in this list are not allowed.
  1715. defaults: dict
  1716. Default values of input parameters.
  1717. Returns
  1718. -------
  1719. kwds : dict
  1720. Input parameters with correct values.
  1721. Raises
  1722. ------
  1723. ValueError :
  1724. If a delimiter was specified with ``sep`` (or ``delimiter``) and
  1725. ``delim_whitespace=True``.
  1726. """
  1727. # fix types for sep, delimiter to Union(str, Any)
  1728. delim_default = defaults["delimiter"]
  1729. kwds: dict[str, Any] = {}
  1730. # gh-23761
  1731. #
  1732. # When a dialect is passed, it overrides any of the overlapping
  1733. # parameters passed in directly. We don't want to warn if the
  1734. # default parameters were passed in (since it probably means
  1735. # that the user didn't pass them in explicitly in the first place).
  1736. #
  1737. # "delimiter" is the annoying corner case because we alias it to
  1738. # "sep" before doing comparison to the dialect values later on.
  1739. # Thus, we need a flag to indicate that we need to "override"
  1740. # the comparison to dialect values by checking if default values
  1741. # for BOTH "delimiter" and "sep" were provided.
  1742. if dialect is not None:
  1743. kwds["sep_override"] = delimiter is None and (
  1744. sep is lib.no_default or sep == delim_default
  1745. )
  1746. if delimiter and (sep is not lib.no_default):
  1747. raise ValueError("Specified a sep and a delimiter; you can only specify one.")
  1748. kwds["names"] = None if names is lib.no_default else names
  1749. # Alias sep -> delimiter.
  1750. if delimiter is None:
  1751. delimiter = sep
  1752. if delim_whitespace and (delimiter is not lib.no_default):
  1753. raise ValueError(
  1754. "Specified a delimiter with both sep and "
  1755. "delim_whitespace=True; you can only specify one."
  1756. )
  1757. if delimiter == "\n":
  1758. raise ValueError(
  1759. r"Specified \n as separator or delimiter. This forces the python engine "
  1760. "which does not accept a line terminator. Hence it is not allowed to use "
  1761. "the line terminator as separator.",
  1762. )
  1763. if delimiter is lib.no_default:
  1764. # assign default separator value
  1765. kwds["delimiter"] = delim_default
  1766. else:
  1767. kwds["delimiter"] = delimiter
  1768. if engine is not None:
  1769. kwds["engine_specified"] = True
  1770. else:
  1771. kwds["engine"] = "c"
  1772. kwds["engine_specified"] = False
  1773. if on_bad_lines == "error":
  1774. kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.ERROR
  1775. elif on_bad_lines == "warn":
  1776. kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.WARN
  1777. elif on_bad_lines == "skip":
  1778. kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.SKIP
  1779. elif callable(on_bad_lines):
  1780. if engine != "python":
  1781. raise ValueError(
  1782. "on_bad_line can only be a callable function if engine='python'"
  1783. )
  1784. kwds["on_bad_lines"] = on_bad_lines
  1785. else:
  1786. raise ValueError(f"Argument {on_bad_lines} is invalid for on_bad_lines")
  1787. check_dtype_backend(dtype_backend)
  1788. kwds["dtype_backend"] = dtype_backend
  1789. return kwds
  1790. def _extract_dialect(kwds: dict[str, Any]) -> csv.Dialect | None:
  1791. """
  1792. Extract concrete csv dialect instance.
  1793. Returns
  1794. -------
  1795. csv.Dialect or None
  1796. """
  1797. if kwds.get("dialect") is None:
  1798. return None
  1799. dialect = kwds["dialect"]
  1800. if dialect in csv.list_dialects():
  1801. dialect = csv.get_dialect(dialect)
  1802. _validate_dialect(dialect)
  1803. return dialect
  1804. MANDATORY_DIALECT_ATTRS = (
  1805. "delimiter",
  1806. "doublequote",
  1807. "escapechar",
  1808. "skipinitialspace",
  1809. "quotechar",
  1810. "quoting",
  1811. )
  1812. def _validate_dialect(dialect: csv.Dialect) -> None:
  1813. """
  1814. Validate csv dialect instance.
  1815. Raises
  1816. ------
  1817. ValueError
  1818. If incorrect dialect is provided.
  1819. """
  1820. for param in MANDATORY_DIALECT_ATTRS:
  1821. if not hasattr(dialect, param):
  1822. raise ValueError(f"Invalid dialect {dialect} provided")
  1823. def _merge_with_dialect_properties(
  1824. dialect: csv.Dialect,
  1825. defaults: dict[str, Any],
  1826. ) -> dict[str, Any]:
  1827. """
  1828. Merge default kwargs in TextFileReader with dialect parameters.
  1829. Parameters
  1830. ----------
  1831. dialect : csv.Dialect
  1832. Concrete csv dialect. See csv.Dialect documentation for more details.
  1833. defaults : dict
  1834. Keyword arguments passed to TextFileReader.
  1835. Returns
  1836. -------
  1837. kwds : dict
  1838. Updated keyword arguments, merged with dialect parameters.
  1839. """
  1840. kwds = defaults.copy()
  1841. for param in MANDATORY_DIALECT_ATTRS:
  1842. dialect_val = getattr(dialect, param)
  1843. parser_default = parser_defaults[param]
  1844. provided = kwds.get(param, parser_default)
  1845. # Messages for conflicting values between the dialect
  1846. # instance and the actual parameters provided.
  1847. conflict_msgs = []
  1848. # Don't warn if the default parameter was passed in,
  1849. # even if it conflicts with the dialect (gh-23761).
  1850. if provided not in (parser_default, dialect_val):
  1851. msg = (
  1852. f"Conflicting values for '{param}': '{provided}' was "
  1853. f"provided, but the dialect specifies '{dialect_val}'. "
  1854. "Using the dialect-specified value."
  1855. )
  1856. # Annoying corner case for not warning about
  1857. # conflicts between dialect and delimiter parameter.
  1858. # Refer to the outer "_read_" function for more info.
  1859. if not (param == "delimiter" and kwds.pop("sep_override", False)):
  1860. conflict_msgs.append(msg)
  1861. if conflict_msgs:
  1862. warnings.warn(
  1863. "\n\n".join(conflict_msgs), ParserWarning, stacklevel=find_stack_level()
  1864. )
  1865. kwds[param] = dialect_val
  1866. return kwds
  1867. def _validate_skipfooter(kwds: dict[str, Any]) -> None:
  1868. """
  1869. Check whether skipfooter is compatible with other kwargs in TextFileReader.
  1870. Parameters
  1871. ----------
  1872. kwds : dict
  1873. Keyword arguments passed to TextFileReader.
  1874. Raises
  1875. ------
  1876. ValueError
  1877. If skipfooter is not compatible with other parameters.
  1878. """
  1879. if kwds.get("skipfooter"):
  1880. if kwds.get("iterator") or kwds.get("chunksize"):
  1881. raise ValueError("'skipfooter' not supported for iteration")
  1882. if kwds.get("nrows"):
  1883. raise ValueError("'skipfooter' not supported with 'nrows'")