-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
BUG/ENH: compression for google cloud storage in to_csv #35681
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
Merged
+321
−130
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
20bd678
to_csv: infer compression before potentially converting to file object;
twoertwein 935fc4b
bind input type of encding and mode with the returned type; removed i…
twoertwein 475e8e8
use named tuple; remove some unused variables; closed some file handl…
twoertwein File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,12 +27,17 @@ | |
uses_params, | ||
uses_relative, | ||
) | ||
import warnings | ||
import zipfile | ||
|
||
from pandas._typing import ( | ||
CompressionDict, | ||
CompressionOptions, | ||
EncodingVar, | ||
FileOrBuffer, | ||
FilePathOrBuffer, | ||
IOargs, | ||
ModeVar, | ||
StorageOptions, | ||
) | ||
from pandas.compat import _get_lzma_file, _import_lzma | ||
|
@@ -69,9 +74,7 @@ def is_url(url) -> bool: | |
return parse_url(url).scheme in _VALID_URLS | ||
|
||
|
||
def _expand_user( | ||
filepath_or_buffer: FilePathOrBuffer[AnyStr], | ||
) -> FilePathOrBuffer[AnyStr]: | ||
def _expand_user(filepath_or_buffer: FileOrBuffer[AnyStr]) -> FileOrBuffer[AnyStr]: | ||
""" | ||
Return the argument with an initial component of ~ or ~user | ||
replaced by that user's home directory. | ||
|
@@ -101,7 +104,7 @@ def validate_header_arg(header) -> None: | |
|
||
def stringify_path( | ||
filepath_or_buffer: FilePathOrBuffer[AnyStr], | ||
) -> FilePathOrBuffer[AnyStr]: | ||
) -> FileOrBuffer[AnyStr]: | ||
""" | ||
Attempt to convert a path-like object to a string. | ||
|
||
|
@@ -134,9 +137,9 @@ def stringify_path( | |
# "__fspath__" [union-attr] | ||
# error: Item "IO[bytes]" of "Union[str, Path, IO[bytes]]" has no | ||
# attribute "__fspath__" [union-attr] | ||
return filepath_or_buffer.__fspath__() # type: ignore[union-attr] | ||
filepath_or_buffer = filepath_or_buffer.__fspath__() # type: ignore[union-attr] | ||
elif isinstance(filepath_or_buffer, pathlib.Path): | ||
return str(filepath_or_buffer) | ||
filepath_or_buffer = str(filepath_or_buffer) | ||
return _expand_user(filepath_or_buffer) | ||
|
||
|
||
|
@@ -162,13 +165,13 @@ def is_fsspec_url(url: FilePathOrBuffer) -> bool: | |
) | ||
|
||
|
||
def get_filepath_or_buffer( | ||
def get_filepath_or_buffer( # type: ignore[assignment] | ||
filepath_or_buffer: FilePathOrBuffer, | ||
encoding: Optional[str] = None, | ||
encoding: EncodingVar = None, | ||
compression: CompressionOptions = None, | ||
mode: Optional[str] = None, | ||
mode: ModeVar = None, | ||
storage_options: StorageOptions = None, | ||
): | ||
) -> IOargs[ModeVar, EncodingVar]: | ||
""" | ||
If the filepath_or_buffer is a url, translate and return the buffer. | ||
Otherwise passthrough. | ||
|
@@ -191,14 +194,35 @@ def get_filepath_or_buffer( | |
|
||
.. versionadded:: 1.2.0 | ||
|
||
Returns | ||
------- | ||
Tuple[FilePathOrBuffer, str, CompressionOptions, bool] | ||
Tuple containing the filepath or buffer, the encoding, the compression | ||
and should_close. | ||
..versionchange:: 1.2.0 | ||
twoertwein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Returns the dataclass IOargs. | ||
""" | ||
filepath_or_buffer = stringify_path(filepath_or_buffer) | ||
|
||
# bz2 and xz do not write the byte order mark for utf-16 and utf-32 | ||
# print a warning when writing such files | ||
compression_method = infer_compression( | ||
filepath_or_buffer, get_compression_method(compression)[0] | ||
) | ||
if ( | ||
mode | ||
and "w" in mode | ||
and compression_method in ["bz2", "xz"] | ||
and encoding in ["utf-16", "utf-32"] | ||
): | ||
warnings.warn( | ||
f"{compression} will not write the byte order mark for {encoding}", | ||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||
UnicodeWarning, | ||
) | ||
|
||
# Use binary mode when converting path-like objects to file-like objects (fsspec) | ||
# except when text mode is explicitly requested. The original mode is returned if | ||
# fsspec is not used. | ||
fsspec_mode = mode or "rb" | ||
if "t" not in fsspec_mode and "b" not in fsspec_mode: | ||
fsspec_mode += "b" | ||
|
||
if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer): | ||
# TODO: fsspec can also handle HTTP via requests, but leaving this unchanged | ||
if storage_options: | ||
|
@@ -212,7 +236,13 @@ def get_filepath_or_buffer( | |
compression = "gzip" | ||
reader = BytesIO(req.read()) | ||
req.close() | ||
return reader, encoding, compression, True | ||
return IOargs( | ||
filepath_or_buffer=reader, | ||
encoding=encoding, | ||
compression=compression, | ||
should_close=True, | ||
mode=fsspec_mode, | ||
) | ||
|
||
if is_fsspec_url(filepath_or_buffer): | ||
assert isinstance( | ||
|
@@ -244,7 +274,7 @@ def get_filepath_or_buffer( | |
|
||
try: | ||
file_obj = fsspec.open( | ||
filepath_or_buffer, mode=mode or "rb", **(storage_options or {}) | ||
filepath_or_buffer, mode=fsspec_mode, **(storage_options or {}) | ||
).open() | ||
# GH 34626 Reads from Public Buckets without Credentials needs anon=True | ||
except tuple(err_types_to_retry_with_anon): | ||
|
@@ -255,23 +285,41 @@ def get_filepath_or_buffer( | |
storage_options = dict(storage_options) | ||
storage_options["anon"] = True | ||
file_obj = fsspec.open( | ||
filepath_or_buffer, mode=mode or "rb", **(storage_options or {}) | ||
filepath_or_buffer, mode=fsspec_mode, **(storage_options or {}) | ||
).open() | ||
|
||
return file_obj, encoding, compression, True | ||
return IOargs( | ||
filepath_or_buffer=file_obj, | ||
encoding=encoding, | ||
compression=compression, | ||
should_close=True, | ||
mode=fsspec_mode, | ||
) | ||
elif storage_options: | ||
raise ValueError( | ||
"storage_options passed with file object or non-fsspec file path" | ||
) | ||
|
||
if isinstance(filepath_or_buffer, (str, bytes, mmap.mmap)): | ||
return _expand_user(filepath_or_buffer), None, compression, False | ||
return IOargs( | ||
filepath_or_buffer=_expand_user(filepath_or_buffer), | ||
encoding=encoding, | ||
compression=compression, | ||
should_close=False, | ||
mode=mode, | ||
) | ||
|
||
if not is_file_like(filepath_or_buffer): | ||
msg = f"Invalid file path or buffer object type: {type(filepath_or_buffer)}" | ||
raise ValueError(msg) | ||
|
||
return filepath_or_buffer, None, compression, False | ||
return IOargs( | ||
filepath_or_buffer=filepath_or_buffer, | ||
encoding=encoding, | ||
compression=compression, | ||
should_close=False, | ||
mode=mode, | ||
) | ||
|
||
|
||
def file_path_to_url(path: str) -> str: | ||
|
@@ -452,6 +500,15 @@ def get_handle( | |
need_text_wrapping = (BufferedIOBase, RawIOBase, S3File) | ||
except ImportError: | ||
need_text_wrapping = (BufferedIOBase, RawIOBase) | ||
# fsspec is an optional dependency. If it is available, add its file-object | ||
# class to the list of classes that need text wrapping. If fsspec is too old and is | ||
# needed, get_filepath_or_buffer would already have thrown an exception. | ||
try: | ||
twoertwein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from fsspec.spec import AbstractFileSystem | ||
|
||
need_text_wrapping = (*need_text_wrapping, AbstractFileSystem) | ||
except ImportError: | ||
pass | ||
twoertwein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
handles: List[Union[IO, _MMapWrapper]] = list() | ||
f = path_or_buf | ||
|
@@ -583,12 +640,15 @@ def __init__( | |
self.archive_name = archive_name | ||
kwargs_zip: Dict[str, Any] = {"compression": zipfile.ZIP_DEFLATED} | ||
kwargs_zip.update(kwargs) | ||
super().__init__(file, mode, **kwargs_zip) | ||
super().__init__(file, mode, **kwargs_zip) # type: ignore[arg-type] | ||
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. complains about |
||
|
||
def write(self, data): | ||
archive_name = self.filename | ||
if self.archive_name is not None: | ||
archive_name = self.archive_name | ||
if archive_name is None: | ||
# ZipFile needs a non-empty string | ||
archive_name = "zip" | ||
twoertwein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
super().writestr(archive_name, data) | ||
|
||
@property | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
my local mypy needs that for line 170 and 172 but the CI mypy needs it apparently at that line (
TypeVar
s cannot have default values, could be fixed with@overload
)