Last active
August 29, 2015 13:58
-
-
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
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
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