common.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. """Common I/O API utilities"""
  2. from __future__ import annotations
  3. from abc import (
  4. ABC,
  5. abstractmethod,
  6. )
  7. import codecs
  8. from collections import defaultdict
  9. from collections.abc import (
  10. Hashable,
  11. Mapping,
  12. Sequence,
  13. )
  14. import dataclasses
  15. import functools
  16. import gzip
  17. from io import (
  18. BufferedIOBase,
  19. BytesIO,
  20. RawIOBase,
  21. StringIO,
  22. TextIOBase,
  23. TextIOWrapper,
  24. )
  25. import mmap
  26. import os
  27. from pathlib import Path
  28. import re
  29. import tarfile
  30. from typing import (
  31. IO,
  32. TYPE_CHECKING,
  33. Any,
  34. AnyStr,
  35. DefaultDict,
  36. Generic,
  37. Literal,
  38. TypeVar,
  39. cast,
  40. overload,
  41. )
  42. from urllib.parse import (
  43. urljoin,
  44. urlparse as parse_url,
  45. uses_netloc,
  46. uses_params,
  47. uses_relative,
  48. )
  49. import warnings
  50. import zipfile
  51. from pandas._typing import (
  52. BaseBuffer,
  53. ReadCsvBuffer,
  54. )
  55. from pandas.compat._optional import import_optional_dependency
  56. from pandas.util._exceptions import find_stack_level
  57. from pandas.core.dtypes.common import (
  58. is_bool,
  59. is_file_like,
  60. is_integer,
  61. is_list_like,
  62. )
  63. from pandas.core.dtypes.generic import ABCMultiIndex
  64. _VALID_URLS = set(uses_relative + uses_netloc + uses_params)
  65. _VALID_URLS.discard("")
  66. _FSSPEC_URL_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9+\-+.]*(::[A-Za-z0-9+\-+.]+)*://")
  67. BaseBufferT = TypeVar("BaseBufferT", bound=BaseBuffer)
  68. if TYPE_CHECKING:
  69. from types import TracebackType
  70. from pandas._typing import (
  71. CompressionDict,
  72. CompressionOptions,
  73. FilePath,
  74. ReadBuffer,
  75. StorageOptions,
  76. WriteBuffer,
  77. )
  78. from pandas import MultiIndex
  79. @dataclasses.dataclass
  80. class IOArgs:
  81. """
  82. Return value of io/common.py:_get_filepath_or_buffer.
  83. """
  84. filepath_or_buffer: str | BaseBuffer
  85. encoding: str
  86. mode: str
  87. compression: CompressionDict
  88. should_close: bool = False
  89. @dataclasses.dataclass
  90. class IOHandles(Generic[AnyStr]):
  91. """
  92. Return value of io/common.py:get_handle
  93. Can be used as a context manager.
  94. This is used to easily close created buffers and to handle corner cases when
  95. TextIOWrapper is inserted.
  96. handle: The file handle to be used.
  97. created_handles: All file handles that are created by get_handle
  98. is_wrapped: Whether a TextIOWrapper needs to be detached.
  99. """
  100. # handle might not implement the IO-interface
  101. handle: IO[AnyStr]
  102. compression: CompressionDict
  103. created_handles: list[IO[bytes] | IO[str]] = dataclasses.field(default_factory=list)
  104. is_wrapped: bool = False
  105. def close(self) -> None:
  106. """
  107. Close all created buffers.
  108. Note: If a TextIOWrapper was inserted, it is flushed and detached to
  109. avoid closing the potentially user-created buffer.
  110. """
  111. if self.is_wrapped:
  112. assert isinstance(self.handle, TextIOWrapper)
  113. self.handle.flush()
  114. self.handle.detach()
  115. self.created_handles.remove(self.handle)
  116. for handle in self.created_handles:
  117. handle.close()
  118. self.created_handles = []
  119. self.is_wrapped = False
  120. def __enter__(self) -> IOHandles[AnyStr]:
  121. return self
  122. def __exit__(
  123. self,
  124. exc_type: type[BaseException] | None,
  125. exc_value: BaseException | None,
  126. traceback: TracebackType | None,
  127. ) -> None:
  128. self.close()
  129. def is_url(url: object) -> bool:
  130. """
  131. Check to see if a URL has a valid protocol.
  132. Parameters
  133. ----------
  134. url : str or unicode
  135. Returns
  136. -------
  137. isurl : bool
  138. If `url` has a valid protocol return True otherwise False.
  139. """
  140. if not isinstance(url, str):
  141. return False
  142. return parse_url(url).scheme in _VALID_URLS
  143. @overload
  144. def _expand_user(filepath_or_buffer: str) -> str: ...
  145. @overload
  146. def _expand_user(filepath_or_buffer: BaseBufferT) -> BaseBufferT: ...
  147. def _expand_user(filepath_or_buffer: str | BaseBufferT) -> str | BaseBufferT:
  148. """
  149. Return the argument with an initial component of ~ or ~user
  150. replaced by that user's home directory.
  151. Parameters
  152. ----------
  153. filepath_or_buffer : object to be converted if possible
  154. Returns
  155. -------
  156. expanded_filepath_or_buffer : an expanded filepath or the
  157. input if not expandable
  158. """
  159. if isinstance(filepath_or_buffer, str):
  160. return os.path.expanduser(filepath_or_buffer)
  161. return filepath_or_buffer
  162. def validate_header_arg(header: object) -> None:
  163. if header is None:
  164. return
  165. if is_integer(header):
  166. header = cast(int, header)
  167. if header < 0:
  168. # GH 27779
  169. raise ValueError(
  170. "Passing negative integer to header is invalid. "
  171. "For no header, use header=None instead"
  172. )
  173. return
  174. if is_list_like(header, allow_sets=False):
  175. header = cast(Sequence, header)
  176. if not all(map(is_integer, header)):
  177. raise ValueError("header must be integer or list of integers")
  178. if any(i < 0 for i in header):
  179. raise ValueError("cannot specify multi-index header with negative integers")
  180. return
  181. if is_bool(header):
  182. raise TypeError(
  183. "Passing a bool to header is invalid. Use header=None for no header or "
  184. "header=int or list-like of ints to specify "
  185. "the row(s) making up the column names"
  186. )
  187. # GH 16338
  188. raise ValueError("header must be integer or list of integers")
  189. @overload
  190. def stringify_path(
  191. filepath_or_buffer: FilePath, convert_file_like: bool = ...
  192. ) -> str: ...
  193. @overload
  194. def stringify_path(
  195. filepath_or_buffer: BaseBufferT, convert_file_like: bool = ...
  196. ) -> BaseBufferT: ...
  197. def stringify_path(
  198. filepath_or_buffer: FilePath | BaseBufferT,
  199. convert_file_like: bool = False,
  200. ) -> str | BaseBufferT:
  201. """
  202. Attempt to convert a path-like object to a string.
  203. Parameters
  204. ----------
  205. filepath_or_buffer : object to be converted
  206. Returns
  207. -------
  208. str_filepath_or_buffer : maybe a string version of the object
  209. Notes
  210. -----
  211. Objects supporting the fspath protocol are coerced
  212. according to its __fspath__ method.
  213. Any other object is passed through unchanged, which includes bytes,
  214. strings, buffers, or anything else that's not even path-like.
  215. """
  216. if not convert_file_like and is_file_like(filepath_or_buffer):
  217. # GH 38125: some fsspec objects implement os.PathLike but have already opened a
  218. # file. This prevents opening the file a second time. infer_compression calls
  219. # this function with convert_file_like=True to infer the compression.
  220. return cast(BaseBufferT, filepath_or_buffer)
  221. if isinstance(filepath_or_buffer, os.PathLike):
  222. filepath_or_buffer = filepath_or_buffer.__fspath__()
  223. return _expand_user(filepath_or_buffer)
  224. def urlopen(*args: Any, **kwargs: Any) -> Any:
  225. """
  226. Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of
  227. the stdlib.
  228. """
  229. import urllib.request
  230. return urllib.request.urlopen(*args, **kwargs) # noqa: TID251
  231. def is_fsspec_url(url: FilePath | BaseBuffer) -> bool:
  232. """
  233. Returns true if the given URL looks like
  234. something fsspec can handle
  235. """
  236. return (
  237. isinstance(url, str)
  238. and bool(_FSSPEC_URL_PATTERN.match(url))
  239. and not url.startswith(("http://", "https://"))
  240. )
  241. def _get_filepath_or_buffer(
  242. filepath_or_buffer: FilePath | BaseBuffer,
  243. encoding: str = "utf-8",
  244. compression: CompressionOptions | None = None,
  245. mode: str = "r",
  246. storage_options: StorageOptions | None = None,
  247. ) -> IOArgs:
  248. """
  249. If the filepath_or_buffer is a url, translate and return the buffer.
  250. Otherwise passthrough.
  251. Parameters
  252. ----------
  253. filepath_or_buffer : a url, filepath (str or pathlib.Path),
  254. or buffer
  255. compression : str or dict, default 'infer'
  256. For on-the-fly compression of the output data. If 'infer' and
  257. 'filepath_or_buffer' is path-like, then detect compression from the
  258. following extensions: '.gz',
  259. '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
  260. (otherwise no compression).
  261. Set to ``None`` for no compression.
  262. Can also be a dict with key ``'method'`` set
  263. to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}
  264. and other key-value pairs are forwarded to
  265. ``zipfile.ZipFile``, ``gzip.GzipFile``,
  266. ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
  267. ``tarfile.TarFile``, respectively.
  268. As an example, the following could be passed for faster compression and to
  269. create a reproducible gzip archive:
  270. ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
  271. encoding : the encoding to use to decode bytes, default is 'utf-8'
  272. mode : str, optional
  273. storage_options : dict, optional
  274. Extra options that make sense for a particular storage connection, e.g.
  275. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
  276. are forwarded to ``urllib.request.Request`` as header options. For other
  277. URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
  278. forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
  279. details, and for more examples on storage options refer `here
  280. <https://pandas.pydata.org/docs/user_guide/io.html?
  281. highlight=storage_options#reading-writing-remote-files>`_.
  282. Returns the dataclass IOArgs.
  283. """
  284. filepath_or_buffer = stringify_path(filepath_or_buffer)
  285. # handle compression dict
  286. compression_method, compression = get_compression_method(compression)
  287. compression_method = infer_compression(filepath_or_buffer, compression_method)
  288. # GH21227 internal compression is not used for non-binary handles.
  289. if compression_method and hasattr(filepath_or_buffer, "write") and "b" not in mode:
  290. warnings.warn(
  291. "compression has no effect when passing a non-binary object as input.",
  292. RuntimeWarning,
  293. stacklevel=find_stack_level(),
  294. )
  295. compression_method = None
  296. compression = dict(compression, method=compression_method)
  297. # bz2 and xz do not write the byte order mark for utf-16 and utf-32
  298. # print a warning when writing such files
  299. if (
  300. "w" in mode
  301. and compression_method in ["bz2", "xz"]
  302. and encoding in ["utf-16", "utf-32"]
  303. ):
  304. warnings.warn(
  305. f"{compression} will not write the byte order mark for {encoding}",
  306. UnicodeWarning,
  307. stacklevel=find_stack_level(),
  308. )
  309. if "a" in mode and compression_method in ["zip", "tar"]:
  310. # GH56778
  311. warnings.warn(
  312. "zip and tar do not support mode 'a' properly. "
  313. "This combination will result in multiple files with same name "
  314. "being added to the archive.",
  315. RuntimeWarning,
  316. stacklevel=find_stack_level(),
  317. )
  318. # Use binary mode when converting path-like objects to file-like objects (fsspec)
  319. # except when text mode is explicitly requested. The original mode is returned if
  320. # fsspec is not used.
  321. fsspec_mode = mode
  322. if "t" not in fsspec_mode and "b" not in fsspec_mode:
  323. fsspec_mode += "b"
  324. if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer):
  325. # TODO: fsspec can also handle HTTP via requests, but leaving this
  326. # unchanged. using fsspec appears to break the ability to infer if the
  327. # server responded with gzipped data
  328. storage_options = storage_options or {}
  329. # waiting until now for importing to match intended lazy logic of
  330. # urlopen function defined elsewhere in this module
  331. import urllib.request
  332. # assuming storage_options is to be interpreted as headers
  333. req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options)
  334. with urlopen(req_info) as req:
  335. content_encoding = req.headers.get("Content-Encoding", None)
  336. if content_encoding == "gzip":
  337. # Override compression based on Content-Encoding header
  338. compression = {"method": "gzip"}
  339. reader = BytesIO(req.read())
  340. return IOArgs(
  341. filepath_or_buffer=reader,
  342. encoding=encoding,
  343. compression=compression,
  344. should_close=True,
  345. mode=fsspec_mode,
  346. )
  347. if is_fsspec_url(filepath_or_buffer):
  348. assert isinstance(
  349. filepath_or_buffer, str
  350. ) # just to appease mypy for this branch
  351. # two special-case s3-like protocols; these have special meaning in Hadoop,
  352. # but are equivalent to just "s3" from fsspec's point of view
  353. # cc #11071
  354. if filepath_or_buffer.startswith("s3a://"):
  355. filepath_or_buffer = filepath_or_buffer.replace("s3a://", "s3://")
  356. if filepath_or_buffer.startswith("s3n://"):
  357. filepath_or_buffer = filepath_or_buffer.replace("s3n://", "s3://")
  358. fsspec = import_optional_dependency("fsspec")
  359. # If botocore is installed we fallback to reading with anon=True
  360. # to allow reads from public buckets
  361. err_types_to_retry_with_anon: list[Any] = []
  362. try:
  363. import_optional_dependency("botocore")
  364. from botocore.exceptions import (
  365. ClientError,
  366. NoCredentialsError,
  367. )
  368. err_types_to_retry_with_anon = [
  369. ClientError,
  370. NoCredentialsError,
  371. PermissionError,
  372. ]
  373. except ImportError:
  374. pass
  375. try:
  376. file_obj = fsspec.open(
  377. filepath_or_buffer, mode=fsspec_mode, **(storage_options or {})
  378. ).open()
  379. # GH 34626 Reads from Public Buckets without Credentials needs anon=True
  380. except tuple(err_types_to_retry_with_anon):
  381. if storage_options is None:
  382. storage_options = {"anon": True}
  383. else:
  384. # don't mutate user input.
  385. storage_options = dict(storage_options)
  386. storage_options["anon"] = True
  387. file_obj = fsspec.open(
  388. filepath_or_buffer, mode=fsspec_mode, **(storage_options or {})
  389. ).open()
  390. return IOArgs(
  391. filepath_or_buffer=file_obj,
  392. encoding=encoding,
  393. compression=compression,
  394. should_close=True,
  395. mode=fsspec_mode,
  396. )
  397. elif storage_options:
  398. raise ValueError(
  399. "storage_options passed with file object or non-fsspec file path"
  400. )
  401. if isinstance(filepath_or_buffer, (str, bytes, mmap.mmap)):
  402. return IOArgs(
  403. filepath_or_buffer=_expand_user(filepath_or_buffer),
  404. encoding=encoding,
  405. compression=compression,
  406. should_close=False,
  407. mode=mode,
  408. )
  409. # is_file_like requires (read | write) & __iter__ but __iter__ is only
  410. # needed for read_csv(engine=python)
  411. if not (
  412. hasattr(filepath_or_buffer, "read") or hasattr(filepath_or_buffer, "write")
  413. ):
  414. msg = f"Invalid file path or buffer object type: {type(filepath_or_buffer)}"
  415. raise ValueError(msg)
  416. return IOArgs(
  417. filepath_or_buffer=filepath_or_buffer,
  418. encoding=encoding,
  419. compression=compression,
  420. should_close=False,
  421. mode=mode,
  422. )
  423. def file_path_to_url(path: str) -> str:
  424. """
  425. converts an absolute native path to a FILE URL.
  426. Parameters
  427. ----------
  428. path : a path in native format
  429. Returns
  430. -------
  431. a valid FILE URL
  432. """
  433. # lazify expensive import (~30ms)
  434. from urllib.request import pathname2url
  435. return urljoin("file:", pathname2url(path))
  436. extension_to_compression = {
  437. ".tar": "tar",
  438. ".tar.gz": "tar",
  439. ".tar.bz2": "tar",
  440. ".tar.xz": "tar",
  441. ".gz": "gzip",
  442. ".bz2": "bz2",
  443. ".zip": "zip",
  444. ".xz": "xz",
  445. ".zst": "zstd",
  446. }
  447. _supported_compressions = set(extension_to_compression.values())
  448. def get_compression_method(
  449. compression: CompressionOptions,
  450. ) -> tuple[str | None, CompressionDict]:
  451. """
  452. Simplifies a compression argument to a compression method string and
  453. a mapping containing additional arguments.
  454. Parameters
  455. ----------
  456. compression : str or mapping
  457. If string, specifies the compression method. If mapping, value at key
  458. 'method' specifies compression method.
  459. Returns
  460. -------
  461. tuple of ({compression method}, Optional[str]
  462. {compression arguments}, Dict[str, Any])
  463. Raises
  464. ------
  465. ValueError on mapping missing 'method' key
  466. """
  467. compression_method: str | None
  468. if isinstance(compression, Mapping):
  469. compression_args = dict(compression)
  470. try:
  471. compression_method = compression_args.pop("method")
  472. except KeyError as err:
  473. raise ValueError("If mapping, compression must have key 'method'") from err
  474. else:
  475. compression_args = {}
  476. compression_method = compression
  477. return compression_method, compression_args
  478. def infer_compression(
  479. filepath_or_buffer: FilePath | BaseBuffer, compression: str | None
  480. ) -> str | None:
  481. """
  482. Get the compression method for filepath_or_buffer. If compression='infer',
  483. the inferred compression method is returned. Otherwise, the input
  484. compression method is returned unchanged, unless it's invalid, in which
  485. case an error is raised.
  486. Parameters
  487. ----------
  488. filepath_or_buffer : str or file handle
  489. File path or object.
  490. compression : str or dict, default 'infer'
  491. For on-the-fly compression of the output data. If 'infer' and
  492. 'filepath_or_buffer' is path-like, then detect compression from the
  493. following extensions: '.gz',
  494. '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
  495. (otherwise no compression).
  496. Set to ``None`` for no compression.
  497. Can also be a dict with key ``'method'`` set
  498. to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}
  499. and other key-value pairs are forwarded to
  500. ``zipfile.ZipFile``, ``gzip.GzipFile``,
  501. ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
  502. ``tarfile.TarFile``, respectively.
  503. As an example, the following could be passed for faster compression and to
  504. create a reproducible gzip archive:
  505. ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
  506. Returns
  507. -------
  508. string or None
  509. Raises
  510. ------
  511. ValueError on invalid compression specified.
  512. """
  513. if compression is None:
  514. return None
  515. # Infer compression
  516. if compression == "infer":
  517. # Convert all path types (e.g. pathlib.Path) to strings
  518. if isinstance(filepath_or_buffer, str) and "::" in filepath_or_buffer:
  519. # chained URLs contain ::
  520. filepath_or_buffer = filepath_or_buffer.split("::")[0]
  521. filepath_or_buffer = stringify_path(filepath_or_buffer, convert_file_like=True)
  522. if not isinstance(filepath_or_buffer, str):
  523. # Cannot infer compression of a buffer, assume no compression
  524. return None
  525. # Infer compression from the filename/URL extension
  526. for extension, compression in extension_to_compression.items():
  527. if filepath_or_buffer.lower().endswith(extension):
  528. return compression
  529. return None
  530. # Compression has been specified. Check that it's valid
  531. if compression in _supported_compressions:
  532. return compression
  533. valid = ["infer", None, *sorted(_supported_compressions)]
  534. msg = (
  535. f"Unrecognized compression type: {compression}\n"
  536. f"Valid compression types are {valid}"
  537. )
  538. raise ValueError(msg)
  539. def check_parent_directory(path: Path | str) -> None:
  540. """
  541. Check if parent directory of a file exists, raise OSError if it does not
  542. Parameters
  543. ----------
  544. path: Path or str
  545. Path to check parent directory of
  546. """
  547. parent = Path(path).parent
  548. if not parent.is_dir():
  549. raise OSError(rf"Cannot save file into a non-existent directory: '{parent}'")
  550. @overload
  551. def get_handle(
  552. path_or_buf: FilePath | BaseBuffer,
  553. mode: str,
  554. *,
  555. encoding: str | None = ...,
  556. compression: CompressionOptions = ...,
  557. memory_map: bool = ...,
  558. is_text: Literal[False],
  559. errors: str | None = ...,
  560. storage_options: StorageOptions = ...,
  561. ) -> IOHandles[bytes]: ...
  562. @overload
  563. def get_handle(
  564. path_or_buf: FilePath | BaseBuffer,
  565. mode: str,
  566. *,
  567. encoding: str | None = ...,
  568. compression: CompressionOptions = ...,
  569. memory_map: bool = ...,
  570. is_text: Literal[True] = ...,
  571. errors: str | None = ...,
  572. storage_options: StorageOptions = ...,
  573. ) -> IOHandles[str]: ...
  574. @overload
  575. def get_handle(
  576. path_or_buf: FilePath | BaseBuffer,
  577. mode: str,
  578. *,
  579. encoding: str | None = ...,
  580. compression: CompressionOptions = ...,
  581. memory_map: bool = ...,
  582. is_text: bool = ...,
  583. errors: str | None = ...,
  584. storage_options: StorageOptions = ...,
  585. ) -> IOHandles[str] | IOHandles[bytes]: ...
  586. def get_handle(
  587. path_or_buf: FilePath | BaseBuffer,
  588. mode: str,
  589. *,
  590. encoding: str | None = None,
  591. compression: CompressionOptions | None = None,
  592. memory_map: bool = False,
  593. is_text: bool = True,
  594. errors: str | None = None,
  595. storage_options: StorageOptions | None = None,
  596. ) -> IOHandles[str] | IOHandles[bytes]:
  597. """
  598. Get file handle for given path/buffer and mode.
  599. Parameters
  600. ----------
  601. path_or_buf : str or file handle
  602. File path or object.
  603. mode : str
  604. Mode to open path_or_buf with.
  605. encoding : str or None
  606. Encoding to use.
  607. compression : str or dict, default 'infer'
  608. For on-the-fly compression of the output data. If 'infer' and 'path_or_buf'
  609. is path-like, then detect compression from the following extensions: '.gz',
  610. '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
  611. (otherwise no compression).
  612. Set to ``None`` for no compression.
  613. Can also be a dict with key ``'method'`` set
  614. to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}
  615. and other key-value pairs are forwarded to
  616. ``zipfile.ZipFile``, ``gzip.GzipFile``,
  617. ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
  618. ``tarfile.TarFile``, respectively.
  619. As an example, the following could be passed for faster compression and to
  620. create a reproducible gzip archive:
  621. ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
  622. May be a dict with key 'method' as compression mode
  623. and other keys as compression options if compression
  624. mode is 'zip'.
  625. Passing compression options as keys in dict is
  626. supported for compression modes 'gzip', 'bz2', 'zstd' and 'zip'.
  627. memory_map : bool, default False
  628. See parsers._parser_params for more information. Only used by read_csv.
  629. is_text : bool, default True
  630. Whether the type of the content passed to the file/buffer is string or
  631. bytes. This is not the same as `"b" not in mode`. If a string content is
  632. passed to a binary file/buffer, a wrapper is inserted.
  633. errors : str, default 'strict'
  634. Specifies how encoding and decoding errors are to be handled.
  635. See the errors argument for :func:`open` for a full list
  636. of options.
  637. storage_options: StorageOptions = None
  638. Passed to _get_filepath_or_buffer
  639. Returns the dataclass IOHandles
  640. """
  641. # Windows does not default to utf-8. Set to utf-8 for a consistent behavior
  642. encoding = encoding or "utf-8"
  643. errors = errors or "strict"
  644. # read_csv does not know whether the buffer is opened in binary/text mode
  645. if _is_binary_mode(path_or_buf, mode) and "b" not in mode:
  646. mode += "b"
  647. # validate encoding and errors
  648. codecs.lookup(encoding)
  649. if isinstance(errors, str):
  650. codecs.lookup_error(errors)
  651. # open URLs
  652. ioargs = _get_filepath_or_buffer(
  653. path_or_buf,
  654. encoding=encoding,
  655. compression=compression,
  656. mode=mode,
  657. storage_options=storage_options,
  658. )
  659. handle = ioargs.filepath_or_buffer
  660. handles: list[BaseBuffer]
  661. # memory mapping needs to be the first step
  662. # only used for read_csv
  663. handle, memory_map, handles = _maybe_memory_map(handle, memory_map)
  664. is_path = isinstance(handle, str)
  665. compression_args = dict(ioargs.compression)
  666. compression = compression_args.pop("method")
  667. # Only for write methods
  668. if "r" not in mode and is_path:
  669. check_parent_directory(str(handle))
  670. if compression:
  671. if compression != "zstd":
  672. # compression libraries do not like an explicit text-mode
  673. ioargs.mode = ioargs.mode.replace("t", "")
  674. elif compression == "zstd" and "b" not in ioargs.mode:
  675. # python-zstandard defaults to text mode, but we always expect
  676. # compression libraries to use binary mode.
  677. ioargs.mode += "b"
  678. # GZ Compression
  679. if compression == "gzip":
  680. if isinstance(handle, str):
  681. # error: Incompatible types in assignment (expression has type
  682. # "GzipFile", variable has type "Union[str, BaseBuffer]")
  683. handle = gzip.GzipFile( # type: ignore[assignment]
  684. filename=handle,
  685. mode=ioargs.mode,
  686. **compression_args,
  687. )
  688. else:
  689. handle = gzip.GzipFile(
  690. # No overload variant of "GzipFile" matches argument types
  691. # "Union[str, BaseBuffer]", "str", "Dict[str, Any]"
  692. fileobj=handle, # type: ignore[call-overload]
  693. mode=ioargs.mode,
  694. **compression_args,
  695. )
  696. # BZ Compression
  697. elif compression == "bz2":
  698. import bz2
  699. # Overload of "BZ2File" to handle pickle protocol 5
  700. # "Union[str, BaseBuffer]", "str", "Dict[str, Any]"
  701. handle = bz2.BZ2File( # type: ignore[call-overload]
  702. handle,
  703. mode=ioargs.mode,
  704. **compression_args,
  705. )
  706. # ZIP Compression
  707. elif compression == "zip":
  708. # error: Argument 1 to "_BytesZipFile" has incompatible type
  709. # "Union[str, BaseBuffer]"; expected "Union[Union[str, PathLike[str]],
  710. # ReadBuffer[bytes], WriteBuffer[bytes]]"
  711. handle = _BytesZipFile(
  712. handle, # type: ignore[arg-type]
  713. ioargs.mode,
  714. **compression_args,
  715. )
  716. if handle.buffer.mode == "r":
  717. handles.append(handle)
  718. zip_names = handle.buffer.namelist()
  719. if len(zip_names) == 1:
  720. handle = handle.buffer.open(zip_names.pop())
  721. elif not zip_names:
  722. raise ValueError(f"Zero files found in ZIP file {path_or_buf}")
  723. else:
  724. raise ValueError(
  725. "Multiple files found in ZIP file. "
  726. f"Only one file per ZIP: {zip_names}"
  727. )
  728. # TAR Encoding
  729. elif compression == "tar":
  730. compression_args.setdefault("mode", ioargs.mode)
  731. if isinstance(handle, str):
  732. handle = _BytesTarFile(name=handle, **compression_args)
  733. else:
  734. # error: Argument "fileobj" to "_BytesTarFile" has incompatible
  735. # type "BaseBuffer"; expected "Union[ReadBuffer[bytes],
  736. # WriteBuffer[bytes], None]"
  737. handle = _BytesTarFile(
  738. fileobj=handle, # type: ignore[arg-type]
  739. **compression_args,
  740. )
  741. assert isinstance(handle, _BytesTarFile)
  742. if "r" in handle.buffer.mode:
  743. handles.append(handle)
  744. files = handle.buffer.getnames()
  745. if len(files) == 1:
  746. file = handle.buffer.extractfile(files[0])
  747. assert file is not None
  748. handle = file
  749. elif not files:
  750. raise ValueError(f"Zero files found in TAR archive {path_or_buf}")
  751. else:
  752. raise ValueError(
  753. "Multiple files found in TAR archive. "
  754. f"Only one file per TAR archive: {files}"
  755. )
  756. # XZ Compression
  757. elif compression == "xz":
  758. # error: Argument 1 to "LZMAFile" has incompatible type "Union[str,
  759. # BaseBuffer]"; expected "Optional[Union[Union[str, bytes, PathLike[str],
  760. # PathLike[bytes]], IO[bytes]], None]"
  761. import lzma
  762. handle = lzma.LZMAFile(
  763. handle, # type: ignore[arg-type]
  764. ioargs.mode,
  765. **compression_args,
  766. )
  767. # Zstd Compression
  768. elif compression == "zstd":
  769. zstd = import_optional_dependency("zstandard")
  770. if "r" in ioargs.mode:
  771. open_args = {"dctx": zstd.ZstdDecompressor(**compression_args)}
  772. else:
  773. open_args = {"cctx": zstd.ZstdCompressor(**compression_args)}
  774. handle = zstd.open(
  775. handle,
  776. mode=ioargs.mode,
  777. **open_args,
  778. )
  779. # Unrecognized Compression
  780. else:
  781. msg = f"Unrecognized compression type: {compression}"
  782. raise ValueError(msg)
  783. assert not isinstance(handle, str)
  784. handles.append(handle)
  785. elif isinstance(handle, str):
  786. # Check whether the filename is to be opened in binary mode.
  787. # Binary mode does not support 'encoding' and 'newline'.
  788. if ioargs.encoding and "b" not in ioargs.mode:
  789. # Encoding
  790. handle = open(
  791. handle,
  792. ioargs.mode,
  793. encoding=ioargs.encoding,
  794. errors=errors,
  795. newline="",
  796. )
  797. else:
  798. # Binary mode
  799. handle = open(handle, ioargs.mode)
  800. handles.append(handle)
  801. # Convert BytesIO or file objects passed with an encoding
  802. is_wrapped = False
  803. if not is_text and ioargs.mode == "rb" and isinstance(handle, TextIOBase):
  804. # not added to handles as it does not open/buffer resources
  805. handle = _BytesIOWrapper(
  806. handle,
  807. encoding=ioargs.encoding,
  808. )
  809. elif is_text and (
  810. compression or memory_map or _is_binary_mode(handle, ioargs.mode)
  811. ):
  812. if (
  813. not hasattr(handle, "readable")
  814. or not hasattr(handle, "writable")
  815. or not hasattr(handle, "seekable")
  816. ):
  817. handle = _IOWrapper(handle)
  818. # error: Value of type variable "_BufferT_co" of "TextIOWrapper" cannot
  819. # be "_IOWrapper | BaseBuffer" [type-var]
  820. handle = TextIOWrapper(
  821. handle, # type: ignore[type-var]
  822. encoding=ioargs.encoding,
  823. errors=errors,
  824. newline="",
  825. )
  826. handles.append(handle)
  827. # only marked as wrapped when the caller provided a handle
  828. is_wrapped = not (
  829. isinstance(ioargs.filepath_or_buffer, str) or ioargs.should_close
  830. )
  831. if "r" in ioargs.mode and not hasattr(handle, "read"):
  832. raise TypeError(
  833. "Expected file path name or file-like object, "
  834. f"got {type(ioargs.filepath_or_buffer)} type"
  835. )
  836. handles.reverse() # close the most recently added buffer first
  837. if ioargs.should_close:
  838. assert not isinstance(ioargs.filepath_or_buffer, str)
  839. handles.append(ioargs.filepath_or_buffer)
  840. return IOHandles(
  841. # error: Argument "handle" to "IOHandles" has incompatible type
  842. # "Union[TextIOWrapper, GzipFile, BaseBuffer, typing.IO[bytes],
  843. # typing.IO[Any]]"; expected "pandas._typing.IO[Any]"
  844. handle=handle, # type: ignore[arg-type]
  845. # error: Argument "created_handles" to "IOHandles" has incompatible type
  846. # "List[BaseBuffer]"; expected "List[Union[IO[bytes], IO[str]]]"
  847. created_handles=handles, # type: ignore[arg-type]
  848. is_wrapped=is_wrapped,
  849. compression=ioargs.compression,
  850. )
  851. class _BufferedWriter(BytesIO, ABC):
  852. """
  853. Some objects do not support multiple .write() calls (TarFile and ZipFile).
  854. This wrapper writes to the underlying buffer on close.
  855. """
  856. buffer = BytesIO()
  857. @abstractmethod
  858. def write_to_buffer(self) -> None: ...
  859. def close(self) -> None:
  860. if self.closed:
  861. # already closed
  862. return
  863. if self.getbuffer().nbytes:
  864. # write to buffer
  865. self.seek(0)
  866. with self.buffer:
  867. self.write_to_buffer()
  868. else:
  869. self.buffer.close()
  870. super().close()
  871. class _BytesTarFile(_BufferedWriter):
  872. def __init__(
  873. self,
  874. name: str | None = None,
  875. mode: Literal["r", "a", "w", "x"] = "r",
  876. fileobj: ReadBuffer[bytes] | WriteBuffer[bytes] | None = None,
  877. archive_name: str | None = None,
  878. **kwargs: Any,
  879. ) -> None:
  880. super().__init__()
  881. self.archive_name = archive_name
  882. self.name = name
  883. # error: No overload variant of "open" of "TarFile" matches argument
  884. # types "str | None", "str", "ReadBuffer[bytes] | WriteBuffer[bytes] | None",
  885. # "dict[str, Any]"
  886. # error: Incompatible types in assignment (expression has type "TarFile",
  887. # base class "_BufferedWriter" defined the type as "BytesIO")
  888. self.buffer: tarfile.TarFile = tarfile.TarFile.open( # type: ignore[call-overload, assignment]
  889. name=name,
  890. mode=self.extend_mode(mode),
  891. fileobj=fileobj,
  892. **kwargs,
  893. )
  894. def extend_mode(self, mode: str) -> str:
  895. mode = mode.replace("b", "")
  896. if mode != "w":
  897. return mode
  898. if self.name is not None:
  899. suffix = Path(self.name).suffix
  900. if suffix in (".gz", ".xz", ".bz2"):
  901. mode = f"{mode}:{suffix[1:]}"
  902. return mode
  903. def infer_filename(self) -> str | None:
  904. """
  905. If an explicit archive_name is not given, we still want the file inside the zip
  906. file not to be named something.tar, because that causes confusion (GH39465).
  907. """
  908. if self.name is None:
  909. return None
  910. filename = Path(self.name)
  911. if filename.suffix == ".tar":
  912. return filename.with_suffix("").name
  913. elif filename.suffix in (".tar.gz", ".tar.bz2", ".tar.xz"):
  914. return filename.with_suffix("").with_suffix("").name
  915. return filename.name
  916. def write_to_buffer(self) -> None:
  917. # TarFile needs a non-empty string
  918. archive_name = self.archive_name or self.infer_filename() or "tar"
  919. tarinfo = tarfile.TarInfo(name=archive_name)
  920. tarinfo.size = len(self.getvalue())
  921. self.buffer.addfile(tarinfo, self)
  922. class _BytesZipFile(_BufferedWriter):
  923. def __init__(
  924. self,
  925. file: FilePath | ReadBuffer[bytes] | WriteBuffer[bytes],
  926. mode: str,
  927. archive_name: str | None = None,
  928. **kwargs: Any,
  929. ) -> None:
  930. super().__init__()
  931. mode = mode.replace("b", "")
  932. self.archive_name = archive_name
  933. kwargs.setdefault("compression", zipfile.ZIP_DEFLATED)
  934. # error: No overload variant of "ZipFile" matches argument types
  935. # "str | PathLike[str] | ReadBuffer[bytes] | WriteBuffer[bytes]",
  936. # "str", "dict[str, Any]"
  937. # error: Incompatible types in assignment (expression has type "ZipFile",
  938. # base class "_BufferedWriter" defined the type as "BytesIO")
  939. self.buffer: zipfile.ZipFile = zipfile.ZipFile( # type: ignore[call-overload, assignment]
  940. file, mode, **kwargs
  941. )
  942. def infer_filename(self) -> str | None:
  943. """
  944. If an explicit archive_name is not given, we still want the file inside the zip
  945. file not to be named something.zip, because that causes confusion (GH39465).
  946. """
  947. if isinstance(self.buffer.filename, (os.PathLike, str)):
  948. filename = Path(self.buffer.filename)
  949. if filename.suffix == ".zip":
  950. return filename.with_suffix("").name
  951. return filename.name
  952. return None
  953. def write_to_buffer(self) -> None:
  954. # ZipFile needs a non-empty string
  955. archive_name = self.archive_name or self.infer_filename() or "zip"
  956. self.buffer.writestr(archive_name, self.getvalue())
  957. class _IOWrapper:
  958. # TextIOWrapper is overly strict: it request that the buffer has seekable, readable,
  959. # and writable. If we have a read-only buffer, we shouldn't need writable and vice
  960. # versa. Some buffers, are seek/read/writ-able but they do not have the "-able"
  961. # methods, e.g., tempfile.SpooledTemporaryFile.
  962. # If a buffer does not have the above "-able" methods, we simple assume they are
  963. # seek/read/writ-able.
  964. def __init__(self, buffer: BaseBuffer) -> None:
  965. self.buffer = buffer
  966. def __getattr__(self, name: str) -> Any:
  967. return getattr(self.buffer, name)
  968. def readable(self) -> bool:
  969. if hasattr(self.buffer, "readable"):
  970. return self.buffer.readable()
  971. return True
  972. def seekable(self) -> bool:
  973. if hasattr(self.buffer, "seekable"):
  974. return self.buffer.seekable()
  975. return True
  976. def writable(self) -> bool:
  977. if hasattr(self.buffer, "writable"):
  978. return self.buffer.writable()
  979. return True
  980. class _BytesIOWrapper:
  981. # Wrapper that wraps a StringIO buffer and reads bytes from it
  982. # Created for compat with pyarrow read_csv
  983. def __init__(self, buffer: StringIO | TextIOBase, encoding: str = "utf-8") -> None:
  984. self.buffer = buffer
  985. self.encoding = encoding
  986. # Because a character can be represented by more than 1 byte,
  987. # it is possible that reading will produce more bytes than n
  988. # We store the extra bytes in this overflow variable, and append the
  989. # overflow to the front of the bytestring the next time reading is performed
  990. self.overflow = b""
  991. def __getattr__(self, attr: str) -> Any:
  992. return getattr(self.buffer, attr)
  993. def read(self, n: int | None = -1) -> bytes:
  994. assert self.buffer is not None
  995. bytestring = self.buffer.read(n).encode(self.encoding)
  996. # When n=-1/n greater than remaining bytes: Read entire file/rest of file
  997. combined_bytestring = self.overflow + bytestring
  998. if n is None or n < 0 or n >= len(combined_bytestring):
  999. self.overflow = b""
  1000. return combined_bytestring
  1001. else:
  1002. to_return = combined_bytestring[:n]
  1003. self.overflow = combined_bytestring[n:]
  1004. return to_return
  1005. def _maybe_memory_map(
  1006. handle: str | BaseBuffer, memory_map: bool
  1007. ) -> tuple[str | BaseBuffer, bool, list[BaseBuffer]]:
  1008. """Try to memory map file/buffer."""
  1009. handles: list[BaseBuffer] = []
  1010. memory_map &= hasattr(handle, "fileno") or isinstance(handle, str)
  1011. if not memory_map:
  1012. return handle, memory_map, handles
  1013. # mmap used by only read_csv
  1014. handle = cast(ReadCsvBuffer, handle)
  1015. # need to open the file first
  1016. if isinstance(handle, str):
  1017. handle = open(handle, "rb")
  1018. handles.append(handle)
  1019. try:
  1020. # open mmap and adds *-able
  1021. # error: Argument 1 to "_IOWrapper" has incompatible type "mmap";
  1022. # expected "BaseBuffer"
  1023. wrapped = _IOWrapper(
  1024. mmap.mmap(
  1025. handle.fileno(),
  1026. 0,
  1027. access=mmap.ACCESS_READ, # type: ignore[arg-type]
  1028. )
  1029. )
  1030. finally:
  1031. for handle in reversed(handles):
  1032. # error: "BaseBuffer" has no attribute "close"
  1033. handle.close() # type: ignore[attr-defined]
  1034. return wrapped, memory_map, [wrapped]
  1035. def file_exists(filepath_or_buffer: FilePath | BaseBuffer) -> bool:
  1036. """Test whether file exists."""
  1037. exists = False
  1038. filepath_or_buffer = stringify_path(filepath_or_buffer)
  1039. if not isinstance(filepath_or_buffer, str):
  1040. return exists
  1041. try:
  1042. exists = os.path.exists(filepath_or_buffer)
  1043. # gh-5874: if the filepath is too long will raise here
  1044. except (TypeError, ValueError):
  1045. pass
  1046. return exists
  1047. def _is_binary_mode(handle: FilePath | BaseBuffer, mode: str) -> bool:
  1048. """Whether the handle is opened in binary mode"""
  1049. # specified by user
  1050. if "t" in mode or "b" in mode:
  1051. return "b" in mode
  1052. # exceptions
  1053. text_classes = (
  1054. # classes that expect string but have 'b' in mode
  1055. codecs.StreamWriter,
  1056. codecs.StreamReader,
  1057. codecs.StreamReaderWriter,
  1058. )
  1059. if issubclass(type(handle), text_classes):
  1060. return False
  1061. return isinstance(handle, _get_binary_io_classes()) or "b" in getattr(
  1062. handle, "mode", mode
  1063. )
  1064. @functools.lru_cache
  1065. def _get_binary_io_classes() -> tuple[type, ...]:
  1066. """IO classes that that expect bytes"""
  1067. binary_classes: tuple[type, ...] = (BufferedIOBase, RawIOBase)
  1068. # python-zstandard doesn't use any of the builtin base classes; instead we
  1069. # have to use the `zstd.ZstdDecompressionReader` class for isinstance checks.
  1070. # Unfortunately `zstd.ZstdDecompressionReader` isn't exposed by python-zstandard
  1071. # so we have to get it from a `zstd.ZstdDecompressor` instance.
  1072. # See also https://github.com/indygreg/python-zstandard/pull/165.
  1073. zstd = import_optional_dependency("zstandard", errors="ignore")
  1074. if zstd is not None:
  1075. with zstd.ZstdDecompressor().stream_reader(b"") as reader:
  1076. binary_classes += (type(reader),)
  1077. return binary_classes
  1078. def is_potential_multi_index(
  1079. columns: Sequence[Hashable] | MultiIndex,
  1080. index_col: bool | Sequence[int] | None = None,
  1081. ) -> bool:
  1082. """
  1083. Check whether or not the `columns` parameter
  1084. could be converted into a MultiIndex.
  1085. Parameters
  1086. ----------
  1087. columns : array-like
  1088. Object which may or may not be convertible into a MultiIndex
  1089. index_col : None, bool or list, optional
  1090. Column or columns to use as the (possibly hierarchical) index
  1091. Returns
  1092. -------
  1093. bool : Whether or not columns could become a MultiIndex
  1094. """
  1095. if index_col is None or isinstance(index_col, bool):
  1096. index_columns = set()
  1097. else:
  1098. index_columns = set(index_col)
  1099. return bool(
  1100. len(columns)
  1101. and not isinstance(columns, ABCMultiIndex)
  1102. and all(isinstance(c, tuple) for c in columns if c not in index_columns)
  1103. )
  1104. def dedup_names(
  1105. names: Sequence[Hashable], is_potential_multiindex: bool
  1106. ) -> Sequence[Hashable]:
  1107. """
  1108. Rename column names if duplicates exist.
  1109. Currently the renaming is done by appending a period and an autonumeric,
  1110. but a custom pattern may be supported in the future.
  1111. Examples
  1112. --------
  1113. >>> dedup_names(["x", "y", "x", "x"], is_potential_multiindex=False)
  1114. ['x', 'y', 'x.1', 'x.2']
  1115. """
  1116. names = list(names) # so we can index
  1117. counts: DefaultDict[Hashable, int] = defaultdict(int)
  1118. for i, col in enumerate(names):
  1119. cur_count = counts[col]
  1120. while cur_count > 0:
  1121. counts[col] = cur_count + 1
  1122. if is_potential_multiindex:
  1123. # for mypy
  1124. assert isinstance(col, tuple)
  1125. col = (*col[:-1], f"{col[-1]}.{cur_count}")
  1126. else:
  1127. col = f"{col}.{cur_count}"
  1128. cur_count = counts[col]
  1129. names[i] = col
  1130. counts[col] = cur_count + 1
  1131. return names