Skip to content

Instantly share code, notes, and snippets.

@andrewdyates
Created April 24, 2012 17:21
Show Gist options
  • Save andrewdyates/2481682 to your computer and use it in GitHub Desktop.
Save andrewdyates/2481682 to your computer and use it in GitHub Desktop.
Open a file that may be compressed in python.
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