Skip to content

Add ZIP file decompression and TestCompression. #12175

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.18.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ Partial string indexing now matches on ``DateTimeIndex`` when part of a ``MultiI
Other Enhancements
^^^^^^^^^^^^^^^^^^

- ``pd.read_csv()`` now supports opening ZIP files that contains a single CSV (:issue:`12175`)
- ``pd.read_msgpack()`` now always gives writeable ndarrays even when compression is used (:issue:`12359`).

.. _whatsnew_0181.api:
Expand Down
15 changes: 15 additions & 0 deletions pandas/io/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,21 @@ def _get_handle(path, mode, encoding=None, compression=None):
elif compression == 'bz2':
import bz2
f = bz2.BZ2File(path, mode)
elif compression == 'zip':
import zipfile
zip_file = zipfile.ZipFile(path)
zip_names = zip_file.namelist()

if len(zip_names) == 1:
file_name = zip_names.pop()
f = zip_file.open(file_name)
elif len(zip_names) == 0:
raise ValueError('Zero files found in ZIP file {}'
.format(path))
else:
raise ValueError('Multiple files found in ZIP file.'
' Only one file per ZIP :{}'
.format(zip_names))
else:
raise ValueError('Unrecognized compression type: %s' %
compression)
Expand Down
32 changes: 27 additions & 5 deletions pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,12 @@ class ParserWarning(Warning):
information
<http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ on
``iterator`` and ``chunksize``.
compression : {'infer', 'gzip', 'bz2', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer', then use gzip or
bz2 if filepath_or_buffer is a string ending in '.gz' or '.bz2',
respectively, and no decompression otherwise. Set to None for no
decompression.
compression : {'gzip', 'bz2', 'zip', 'infer', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer', then use gzip,
bz2 or zip if filepath_or_buffer is a string ending in '.gz', '.bz2' or
'.zip', respectively, and no decompression otherwise. New in 0.18.1: ZIP
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need a versionadded tag here

compression If using 'zip', the ZIP file must contain only one data file
to be read in. Set to None for no decompression.
thousands : str, default None
Thousands separator
decimal : str, default '.'
Expand Down Expand Up @@ -273,6 +274,8 @@ def _read(filepath_or_buffer, kwds):
inferred_compression = 'gzip'
elif filepath_or_buffer.endswith('.bz2'):
inferred_compression = 'bz2'
elif filepath_or_buffer.endswith('.zip'):
inferred_compression = 'zip'
else:
inferred_compression = None
else:
Expand Down Expand Up @@ -1397,6 +1400,25 @@ def _wrap_compressed(f, compression, encoding=None):
data = bz2.decompress(f.read())
f = StringIO(data)
return f
elif compression == 'zip':
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems quite duplicative (I know it was there before). any way you can simply use _get_handle? (which already has this embeded)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not that trivial. wrap_compressed() handles file objects. I'd have to refactor this code to handle for this. See the logic below

        if isinstance(f, compat.string_types):
            f = _get_handle(f, 'r', encoding=self.encoding,
                            compression=self.compression)
        elif self.compression:
            f = _wrap_compressed(f, self.compression, self.encoding)

I would then have to modify _get_handle to deal with file objects as well as strings

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok then is possible to isolate this so each is just a function call to a common function? (just trying to avoid this code duplication)

import zipfile
zip_file = zipfile.ZipFile(f)
zip_names = zip_file.namelist()
print('ZIPNAMES' + zip_names)

if len(zip_names) == 1:
file_name = zip_names.pop()
f = zip_file.open(file_name)
return f

elif len(zip_names) == 0:
raise ValueError('Corrupted or zero files found in compressed '
'zip file %s', zip_file.filename)

else:
raise ValueError('Multiple files found in compressed '
'zip file %s', str(zip_names))

else:
raise ValueError('do not recognize compression method %s'
% compression)
Expand Down
Loading