B ®@`¥mã @s¼dZddlZddlZddlmZddlZddlZddlmZm Z m Z m Z m Z ddl Z ddlZddlmZmZmZmZmZmZmZmZmZmZddlmZmZmZmZm Z ddl!Z!ddl"Z"ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)ddl*m+Z+m,Z,dd l-m.Z.dd l/m0Z0e,ƒZ1e2e eeƒZ3e3 4d ¡ej5Gd d „d ƒƒZ6ej5Gdd„dƒƒZ7e8dœdd„Z9e'ee'edœdd„Z:ddœdd„Z;dDe(ee8e'edœdd„ZdEe(e?e&e?e)e6d#œd$d%„Z@e?e?d&œd'd(„ZAd)d*d+d,d-œZBe&eee?e%fd.œd/d0„ZCe(ee?ee?d1œd2d3„ZDdFe(e?ee?e&e8e8ee?e)e7d5œ d6d7„ZEGd8d9„d9e"jFe ƒZGGd:d;„d;ejHƒZIe'e8e?e?ee?ee'e8ee$fd<œd=d>„ZJe(e8dœd?d@„ZKe(e?e8dAœdBdC„ZLdS)GzCommon IO api utilitieséN)Úabc)ÚBufferedIOBaseÚBytesIOÚ RawIOBaseÚStringIOÚ TextIOWrapper) ÚIOÚAnyÚAnyStrÚDictÚListÚMappingÚOptionalÚTupleÚUnionÚcast)ÚurljoinÚurlparseÚ uses_netlocÚ uses_paramsÚ uses_relative)ÚBufferÚCompressionDictÚCompressionOptionsÚ FileOrBufferÚFilePathOrBufferÚStorageOptions)Ú get_lzma_fileÚ import_lzma)Úimport_optional_dependency)Ú is_file_likeÚc@s>eZdZUdZeed<eed<eed<eed<dZe ed<dS) ÚIOArgsa) Return value of io/common.py:_get_filepath_or_buffer. Note (copy&past from io/parsers): filepath_or_buffer can be Union[FilePathOrBuffer, s3fs.S3File, gcsfs.GCSFile] though mypy handling of conditional imports is difficult. See https://github.com/python/mypy/issues/1297 Úfilepath_or_bufferÚencodingÚmodeÚ compressionFÚ should_closeN) Ú__name__Ú __module__Ú __qualname__Ú__doc__rÚ__annotations__Ústrrr'Úbool©r/r/ú4/tmp/pip-unpacked-wheel-q9tj5l6a/pandas/io/common.pyr"*s r"c@s~eZdZUdZeed<eed<eje d�Z e eed<dZ e ed<dZe ed<d d œd d „Zdd œd d„Zed dœdd„Zd S)Ú IOHandlesau Return value of io/common.py:get_handle Can be used as a context manager. This is used to easily close created buffers and to handle corner cases when TextIOWrapper is inserted. handle: The file handle to be used. created_handles: All file handles that are created by get_handle is_wrapped: Whether a TextIOWrapper needs to be detached. Úhandler&)Údefault_factoryÚcreated_handlesFÚ is_wrappedÚis_mmapN)Úreturnc Cs~|jr8t|jtƒst‚|j ¡|j ¡|j |j¡yx|jD] }|  ¡qBWWnt t fk rlYnXg|_d|_dS)zµ Close all created buffers. Note: If a TextIOWrapper was inserted, it is flushed and detached to avoid closing the potentially user-created buffer. FN) r5Ú isinstancer2rÚAssertionErrorÚflushÚdetachr4ÚremoveÚcloseÚOSErrorÚ ValueError)Úselfr2r/r/r0r=Qs   zIOHandles.closecCs|S)Nr/)r@r/r/r0Ú __enter__eszIOHandles.__enter__)Úargsr7cGs | ¡dS)N)r=)r@rBr/r/r0Ú__exit__hszIOHandles.__exit__)r(r)r*r+rr,rÚ dataclassesÚfieldÚlistr4r r5r.r6r=rAr rCr/r/r/r0r1<s   r1)r7cCst|tƒsdSt|ƒjtkS)zÚ Check to see if a URL has a valid protocol. Parameters ---------- url : str or unicode Returns ------- isurl : bool If `url` has a valid protocol return True otherwise False. F)r8r-Ú parse_urlÚschemeÚ _VALID_URLS)Úurlr/r/r0Úis_urlls rK)r#r7cCst|tƒrtj |¡S|S)a] Return the argument with an initial component of ~ or ~user replaced by that user's home directory. Parameters ---------- filepath_or_buffer : object to be converted if possible Returns ------- expanded_filepath_or_buffer : an expanded filepath or the input if not expandable )r8r-ÚosÚpathÚ expanduser)r#r/r/r0Ú _expand_user~s  rOcCst|tƒrtdƒ‚dS)Nz–Passing a bool to header is invalid. Use header=None for no header or header=int or list-like of ints to specify the row(s) making up the column names)r8r.Ú TypeError)Úheaderr/r/r0Úvalidate_header_arg‘s rRF)r#Úconvert_file_liker7cCs6|st|ƒrttt|ƒSt|tjƒr.| ¡}t|ƒS)aó Attempt to convert a path-like object to a string. Parameters ---------- filepath_or_buffer : object to be converted Returns ------- str_filepath_or_buffer : maybe a string version of the object Notes ----- Objects supporting the fspath protocol (python 3.6+) are coerced according to its __fspath__ method. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like. ) r rrr r8rLÚPathLikeÚ __fspath__rO)r#rSr/r/r0Ústringify_pathšs   rVcOsddl}|jj||ŽS)z` Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of the stdlib. rN)Úurllib.requestÚrequestÚurlopen)rBÚkwargsÚurllibr/r/r0rY¼srY)rJr7cCst|tƒod|ko| d¡ S)zR Returns true if the given URL looks like something fsspec can handle z://)zhttp://zhttps://)r8r-Ú startswith)rJr/r/r0Ú is_fsspec_urlÆs r]úutf-8Úr)r#r$r&r%Ústorage_optionsr7c Cs¸t|ƒ}t|ƒ\}}t||ƒ}|rHt|dƒrHd|krHtjdtdd�d}t||d�}|dk rl| dd ¡  ¡}d |krš|d krš|d kršt |›d |›�t ¡|}d|kr¶d|kr¶|d7}t |t ƒ�r$t |ƒ�r$|rØtdƒ‚t|ƒ}|j dd¡}|dkrþddi}t| ¡ƒ} | ¡t| ||d|d�St|ƒ�rNt |t ƒ�s>t‚| d¡�rV| dd¡}| d¡�rn| dd¡}tdƒ} g} y&tdƒddlm} m} | | tg} Wntk �r¶YnXy$| j|fd|i|�pÐi—Ž ¡}Wn^t | ƒk �r:|dk�rddi}nt|ƒ}d|d<| j|fd|i|�p,i—Ž ¡}YnXt|||d|d�S|�r\tdƒ‚t |t t!t"j"fƒ�r†tt#|ƒ||d|d�St$|ƒ�s¦dt%|ƒ›�}t|ƒ‚t|||d|d�S) aÐ If the filepath_or_buffer is a url, translate and return the buffer. Otherwise passthrough. Parameters ---------- filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path), or buffer compression : {{'gzip', 'bz2', 'zip', 'xz', None}}, optional encoding : the encoding to use to decode bytes, default is 'utf-8' mode : str, optional storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by ``fsspec``, e.g., starting "s3://", "gcs://". An error will be raised if providing this argument with a local path or a file-like buffer. See the fsspec and backend storage implementation docs for the set of allowed keys and values .. versionadded:: 1.2.0 ..versionchange:: 1.2.0 Returns the dataclass IOArgs. ÚwriteÚbzDcompression has no effect when passing a non-binary object as input.é)Ú stacklevelN)ÚmethodÚ_ú-Úw)Úbz2Úxz)zutf-16zutf-32z( will not write the byte order mark for Útz?storage_options passed with file object or non-fsspec file pathzContent-EncodingÚgzipreT)r#r$r&r'r%zs3a://zs3://zs3n://ÚfsspecZbotocorer)Ú ClientErrorÚNoCredentialsErrorr%ZanonFz)Invalid file path or buffer object type: )&rVÚget_compression_methodÚinfer_compressionÚhasattrÚwarningsÚwarnÚRuntimeWarningÚdictÚreplaceÚlowerÚUnicodeWarningr8r-rKr?rYÚheadersÚgetrÚreadr=r"r]r9r\rZbotocore.exceptionsrnroÚPermissionErrorÚ ImportErrorÚopenÚtupleÚbytesÚmmaprOr Útype)r#r$r&r%r`Úcompression_methodZ fsspec_modeÚreqÚcontent_encodingÚreaderrmZerr_types_to_retry_with_anonrnroZfile_objÚmsgr/r/r0Ú_get_filepath_or_bufferÒs²!              " r‰)rMr7cCsddlm}td||ƒƒS)z© converts an absolute native path to a FILE URL. Parameters ---------- path : a path in native format Returns ------- a valid FILE URL r)Ú pathname2urlzfile:)rWrŠr)rMrŠr/r/r0Úfile_path_to_url~s r‹z.gzz.bz2z.zipz.xz)rlriÚziprj)r&r7c Cs`t|tƒrPt|ƒ}y| d¡}WqXtk rL}ztdƒ|‚Wdd}~XYqXXni}|}||fS)a Simplifies a compression argument to a compression method string and a mapping containing additional arguments. Parameters ---------- compression : str or mapping If string, specifies the compression method. If mapping, value at key 'method' specifies compression method. Returns ------- tuple of ({compression method}, Optional[str] {compression arguments}, Dict[str, Any]) Raises ------ ValueError on mapping missing 'method' key rez.If mapping, compression must have key 'method'N)r8r rvÚpopÚKeyErrorr?)r&Úcompression_argsr„Úerrr/r/r0rp“s rp)r#r&r7cCsš|dkr dS|dkrZt|dd�}t|tƒs.dSx&t ¡D]\}}| ¡ |¡r8|Sq8WdS|tkrf|Sd|›�}ddgttƒ}|d|›�7}t|ƒ‚dS)aÚ Get the compression method for filepath_or_buffer. If compression='infer', the inferred compression method is returned. Otherwise, the input compression method is returned unchanged, unless it's invalid, in which case an error is raised. Parameters ---------- filepath_or_buffer : str or file handle File path or object. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None} If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). Returns ------- string or None Raises ------ ValueError on invalid compression specified. NZinferT)rSzUnrecognized compression type: z Valid compression types are ) rVr8r-Ú_compression_to_extensionÚitemsrxÚendswithÚsortedr?)r#r&Ú extensionrˆZvalidr/r/r0rq¶s    rqT) Ú path_or_bufr%r$r&Ú memory_mapÚis_textÚerrorsr`r7cCsÖ||pd}}t||ƒr(d|kr(|d7}t|||||d�} | j} t| || j| j|ƒ\} }} t| tƒ} t| j ƒ} |   d¡}|�rÎ| j  dd¡| _|dkrÜ| rÂt| tƒs¨t ‚t jf| | jdœ| —Ž} nt jf| | jd œ| —Ž} nÖ|d k�rtj| fd | ji| —Ž} n²|d k�r„t| | jf| Ž} | jd k�r²|  | ¡|  ¡}t|ƒdk�rV|  |  ¡¡} n,t|ƒdk�rttd|›�ƒ‚ntd|›�ƒ‚n.|dk�r ttƒ| | jƒ} nd|›�}t|ƒ‚t| tƒ�rÂt ‚|  | ¡nft| tƒ�r4| j�rd| jk�r|dk�r|dk�rd}t| | j| j|dd�} n t| | jƒ} |  | ¡d}|�r„|�sRt| | jƒ�r„t| | j|dd�} |  | ¡t| jtƒ�p€| j }|  ¡| j�r²t| jtƒ�r¦t ‚|  | j¡t| tƒ�rÂt ‚t| | ||| j d�S)a� Get file handle for given path/buffer and mode. Parameters ---------- path_or_buf : str or file handle File path or object. mode : str Mode to open path_or_buf with. encoding : str or None Encoding to use. compression : str or dict, default None If string, specifies compression mode. If dict, value at key 'method' specifies compression mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). If dict and compression mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options. .. versionchanged:: 1.0.0 May now be a dict with key 'method' as compression mode and other keys as compression options if compression mode is 'zip'. .. versionchanged:: 1.1.0 Passing compression options as keys in dict is now supported for compression modes 'gzip' and 'bz2' as well as 'zip'. memory_map : boolean, default False See parsers._parser_params for more information. is_text : boolean, default True Whether the type of the content passed to the file/buffer is string or bytes. This is not the same as `"b" not in mode`. If a string content is passed to a binary file/buffer, a wrapper is inserted. errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. storage_options: StorageOptions = None Passed to _get_filepath_or_buffer .. versionchanged:: 1.2.0 Returns the dataclass IOHandles zutf-8rb)r$r&r%r`rerkr!rl)Úfilenamer%)Úfileobjr%rir%rŒr_érzZero files found in ZIP file z9Multiple files found in ZIP file. Only one file per ZIP: rjzUnrecognized compression type: Nrw)r$r™ÚnewlineF)r2r4r5r6r&)Ú_is_binary_moder‰r#Ú_maybe_memory_mapr$r%r8r-rvr&r�rwr9rlÚGzipFileriÚBZ2FileÚ _BytesZipFileÚappendÚnamelistÚlenrr?rÚlzmarr'Úreverser1)r–r%r$r&r—r˜r™r`Zencoding_passedZioargsr2ÚhandlesZis_pathr�Z zip_namesrˆr5r/r/r0Ú get_handleës¤<                   r©csbeZdZdZdeeeedœ‡fdd„ Zdd„Zddœ‡fd d „ Z ‡fd d „Z e d d„ƒZ ‡Z S)r¢a  Wrapper for standard library class ZipFile and allow the returned file-like handle to accept byte strings via `write` method. BytesIO provides attributes of file-like object and ZipFile.writestr writes bytes strings into a member of the archive. N)Úfiler%Ú archive_namec sB| dd¡}||_d|_dtji}| |¡tƒj||f|ŽdS)Nrbr!r&)rwr«Úmultiple_write_bufferÚzipfileÚ ZIP_DEFLATEDÚupdateÚsuperÚ__init__)r@rªr%r«rZZ kwargs_zip)Ú __class__r/r0r±Âs    z_BytesZipFile.__init__cCs2|jdkr"t|tƒrtƒntƒ|_|j |¡dS)N)r¬r8r�rrra)r@Údatar/r/r0raÒs z_BytesZipFile.write)r7c sP|jdks|jjrdS|jp$|jp$d}|j�tƒ ||j ¡¡WdQRXdS)NrŒ)r¬Úclosedr«ršr°ÚwritestrÚgetvalue)r@r«)r²r/r0r:Ús z_BytesZipFile.flushcs| ¡tƒ ¡dS)N)r:r°r=)r@)r²r/r0r=äsz_BytesZipFile.closecCs |jdkS)N)Úfp)r@r/r/r0r´èsz_BytesZipFile.closed)N)r(r)r*r+rr-rr±rar:r=Úpropertyr´Ú __classcell__r/r/)r²r0r¢¸s   r¢c@sHeZdZdZedœdd„Zedœdd„Zddœd d „Zedœd d „Z d S)Ú _MMapWrappera Wrapper for the Python's mmap class so that it can be properly read in by Python's csv.reader class. Parameters ---------- f : file object File object to be mapped onto memory. Must support the 'fileno' method or have an equivalent attribute )ÚfcCsNi|_x*dD]"}t||ƒsq t||ƒƒ|j|<q Wtj| ¡dtjd�|_dS)N)ÚseekableÚreadableZ writeabler)Úaccess)Ú attributesrrÚgetattrr‚ÚfilenoZ ACCESS_READ)r@r»Ú attributer/r/r0r±ús   z_MMapWrapper.__init__)Únamecs$ˆˆjkr‡‡fdd„StˆjˆƒS)Ncs ˆjˆS)N)r¿r/)rÃr@r/r0Úóz*_MMapWrapper.__getattr__..)r¿rÀr‚)r@rÃr/)rÃr@r0Ú __getattr__s z_MMapWrapper.__getattr__)r7cCs|S)Nr/)r@r/r/r0Ú__iter__sz_MMapWrapper.__iter__cCs$|j ¡}| d¡}|dkr t‚|S)Nzutf-8r!)r‚ÚreadlineÚdecodeÚ StopIteration)r@Znewbytesr�r/r/r0Ú__next__ s   z_MMapWrapper.__next__N) r(r)r*r+rr±r-rÆrÇrËr/r/r/r0rºís  rº)r2r—r$r%r™r7cCsÀg}|t|dƒpt|tƒM}|s*|||fSt|tƒrh|rTd|krTt||||dd�}n t||ƒ}| |¡y4ttjt|ƒƒ}| ¡|  |¡| |¡|}Wnt k r´d}YnX|||fS)zTry to memory map file/buffer.rÁrbr!)r$r™r�F) rrr8r-rr£rr‚rºr=r<Ú Exception)r2r—r$r%r™r¨Úwrappedr/r/r0rŸs$        rŸc CsHd}t|ƒ}t|tƒs|Sytj |¡}Wnttfk rBYnX|S)zTest whether file exists.F)rVr8r-rLrMÚexistsrPr?)r#rÎr/r/r0Ú file_exists@s rÏ)r2r%r7cCs8tjf}t||ƒrdSttf}t||ƒp6dt|d|ƒkS)z+Whether the handle is opened in binary modeFrbr%)ÚcodecsÚStreamReaderWriterr8rrrÀ)r2r%Z text_classesZbinary_classesr/r/r0ržNs  rž)F)r^Nr_N)NNFTNN)Mr+rirÐÚ collectionsrrDrlÚiorrrrrr‚rLÚtypingrr r r r r rrrrÚ urllib.parserrrGrrrrsr­Zpandas._typingrrrrrrZ pandas.compatrrZpandas.compat._optionalrZpandas.core.dtypes.commonr r¦ÚsetrIÚdiscardZ dataclassr"r1r.rKrOrRrVrYr]r-r‰r‹r‘rprqr©ÚZipFiler¢ÚIteratorrºrŸrÏržr/r/r/r0Úst 0    0   '"6E5-!