-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
ENH: Allow compression in NDFrame.to_csv to be a dict with optional arguments (#26023) #26024
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 32 commits
4e73dc4
ab7620d
2e782f9
83e8834
d238878
b41be54
60ea58c
8ba9082
0a3a9fd
a1cb3f7
af2a96c
5853a28
789751f
5b09e6f
68a2b4d
c856f50
8df6c81
40d0252
18a735d
103c877
b6c34bc
969d387
abfbc0f
04ae25d
9c22652
56a75c2
bbfea34
7717f16
779511e
780eb04
6c4e679
1b567c9
9324b63
7cf65ee
29374f3
6701aa4
0f5489d
e04138e
6f2bf00
865aa81
8d1deee
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,6 +10,7 @@ | |
import mmap | ||
import os | ||
import pathlib | ||
from typing import Any, Dict, Optional, Tuple, Type, Union | ||
from urllib.error import URLError # noqa | ||
from urllib.parse import ( # noqa | ||
urlencode, | ||
|
@@ -22,6 +23,7 @@ | |
from urllib.request import pathname2url, urlopen | ||
import zipfile | ||
|
||
from pandas._typing import FilePathOrBuffer | ||
from pandas.errors import ( # noqa | ||
AbstractMethodError, | ||
DtypeWarning, | ||
|
@@ -242,13 +244,46 @@ def file_path_to_url(path): | |
_compression_to_extension = {"gzip": ".gz", "bz2": ".bz2", "zip": ".zip", "xz": ".xz"} | ||
|
||
|
||
def _get_compression_method( | ||
compression: Optional[Union[str, Dict[str, str]]] | ||
) -> Tuple[Optional[str], Dict[str, str]]: | ||
""" | ||
Simplifies a compression argument to a compression method string and | ||
a dict containing additional arguments. | ||
|
||
Parameters | ||
---------- | ||
compression : str or dict | ||
If string, specifies the compression method. If dict, value at key | ||
'method' specifies compression method. | ||
|
||
Returns | ||
------- | ||
tuple of ({compression method}, Optional[str] | ||
{compression arguments}, Dict[str, str]) | ||
|
||
Raises | ||
------ | ||
ValueError on dict missing 'method' key | ||
""" | ||
# Handle dict | ||
if isinstance(compression, dict): | ||
compression_args = compression.copy() | ||
try: | ||
compression = compression_args.pop("method") | ||
except KeyError: | ||
raise ValueError("If dict, compression must have key 'method'") | ||
else: | ||
compression_args = {} | ||
return compression, compression_args | ||
WillAyd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
def _infer_compression(filepath_or_buffer, compression): | ||
""" | ||
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. | ||
|
||
gfyoung marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Parameters | ||
---------- | ||
filepath_or_buffer : | ||
|
@@ -257,12 +292,10 @@ def _infer_compression(filepath_or_buffer, compression): | |
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 : | ||
compression method | ||
|
||
Raises | ||
------ | ||
ValueError on invalid compression specified | ||
|
@@ -297,7 +330,12 @@ def _infer_compression(filepath_or_buffer, compression): | |
|
||
|
||
def _get_handle( | ||
path_or_buf, mode, encoding=None, compression=None, memory_map=False, is_text=True | ||
path_or_buf, | ||
mode: str, | ||
encoding=None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Couldn't annotate this particular argument due to a minor bug in typeshed. Fixed on master so maybe something we can come back to soon (typeshed updates are pretty quick) |
||
compression: Optional[Union[str, Dict[str, Any]]] = None, | ||
memory_map: bool = False, | ||
is_text: bool = True, | ||
): | ||
""" | ||
Get file handle for given path/buffer and mode. | ||
|
@@ -309,10 +347,21 @@ def _get_handle( | |
mode : str | ||
mode to open path_or_buf with | ||
encoding : str or None | ||
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 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). | ||
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 'zip' or inferred as | ||
'zip', other entries passed as additional compression options. | ||
|
||
.. versionchanged:: 0.25.0 | ||
|
||
May now be a dict with key 'method' as compression mode | ||
and other keys as compression options if compression | ||
mode is 'zip'. | ||
|
||
memory_map : boolean, default False | ||
See parsers._parser_params for more information. | ||
is_text : boolean, default True | ||
|
@@ -326,12 +375,13 @@ def _get_handle( | |
handles : list of file-like objects | ||
A list of file-like object that were opened in this function. | ||
""" | ||
need_text_wrapping = (BytesIO,) # type: Tuple[Type[BytesIO], ...] | ||
try: | ||
from s3fs import S3File | ||
|
||
need_text_wrapping = (BytesIO, S3File) | ||
need_text_wrapping = need_text_wrapping + (S3File,) | ||
except ImportError: | ||
need_text_wrapping = (BytesIO,) | ||
pass | ||
|
||
handles = list() | ||
f = path_or_buf | ||
|
@@ -340,6 +390,7 @@ def _get_handle( | |
path_or_buf = _stringify_path(path_or_buf) | ||
is_path = isinstance(path_or_buf, str) | ||
|
||
compression, compression_args = _get_compression_method(compression) | ||
WillAyd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if is_path: | ||
compression = _infer_compression(path_or_buf, compression) | ||
|
||
|
@@ -361,7 +412,7 @@ def _get_handle( | |
|
||
# ZIP Compression | ||
elif compression == "zip": | ||
zf = BytesZipFile(path_or_buf, mode) | ||
zf = BytesZipFile(path_or_buf, mode, **compression_args) | ||
# Ensure the container is closed as well. | ||
handles.append(zf) | ||
if zf.mode == "w": | ||
|
@@ -435,13 +486,23 @@ class BytesZipFile(zipfile.ZipFile, BytesIO): # type: ignore | |
""" | ||
|
||
# GH 17778 | ||
def __init__(self, file, mode, compression=zipfile.ZIP_DEFLATED, **kwargs): | ||
def __init__( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It might not be clear in the diff but note that I removed the It makes annotations more complex, because the keyword argument unpacking of |
||
self, | ||
file: FilePathOrBuffer, | ||
mode: str, | ||
archive_name: Optional[str] = None, | ||
**kwargs | ||
): | ||
if mode in ["wb", "rb"]: | ||
mode = mode.replace("b", "") | ||
super().__init__(file, mode, compression, **kwargs) | ||
self.archive_name = archive_name | ||
super().__init__(file, mode, zipfile.ZIP_DEFLATED, **kwargs) | ||
|
||
def write(self, data): | ||
super().writestr(self.filename, data) | ||
archive_name = self.filename | ||
if self.archive_name is not None: | ||
archive_name = self.archive_name | ||
super().writestr(archive_name, data) | ||
|
||
@property | ||
def closed(self): | ||
|
Uh oh!
There was an error while loading. Please reload this page.