Skip to content

Instantly share code, notes, and snippets.

@fawkesley
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fawkesley/9929803 to your computer and use it in GitHub Desktop.
Save fawkesley/9929803 to your computer and use it in GitHub Desktop.
Transparently open a file with open or gzip.open depending on file extension
import gzip
import logging
from contextlib import contextmanager
@contextmanager
def open_file(filename, *args, **kwargs):
"""
Detect if a file is gzipped and use the appropriate open method.
"""
if filename.endswith('.gz') or filename.endswith('.gzip'):
logging.debug("Opening gzipped file {}".format(filename))
open_func = gzip.open
else:
logging.debug("Opening plain file {}".format(filename))
open_func = open
with open_func(filename, *args, **kwargs) as f:
yield f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment