Created
April 24, 2012 17:21
-
-
Save andrewdyates/2481682 to your computer and use it in GitHub Desktop.
Open a file that may be compressed in python.
This file contains 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
import gzip | |
import zipfile | |
def open_with_zip(filepath): | |
"""Open a file with .gzip, .zip, or no compression. | |
Returns: | |
[*str] read filepointer of uncompressed file stream | |
""" | |
ext = filepath.lower().rpartition('.')[-1] | |
if ext == "gzip": | |
return gzip.open(filepath, "rb") | |
elif ext == "zip": | |
z = zipfile.ZipFile(filepath, "r") | |
# Return first file in zip. | |
return z.open(z.namelist()[0], "r") | |
else: | |
return open(filepath, "rb") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment