Created
November 10, 2017 19:23
-
-
Save scriptspry/1407458e874f003bc9217050e0938301 to your computer and use it in GitHub Desktop.
Gunzip (Recursively) If Needed
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
| #!/usr/local/bin/python | |
| import os | |
| from os import path | |
| import gzip as _gzip | |
| import zipfile | |
| import sys | |
| def gunzip(gzp): | |
| if not path.exists(gzp): | |
| return 'No such file' | |
| with _gzip.open(gzp, 'rb') as rf: | |
| content = rf.read() | |
| fp = gzp[:-3] if gzp.endswith('.gz') else gzp | |
| with open(fp, 'wb') as wf: | |
| wf.write(content) | |
| return fp | |
| def unzip(zipfn): | |
| z = zipfile.ZipFile(zipfn, 'r') | |
| z.extractall(zipfn.replace('.zip', '')) | |
| z.close() | |
| def _is_gzipped(fp): | |
| """ | |
| Checks if a file is gzipped or not by checking the signature in file | |
| See http://stackoverflow.com/a/13044946 | |
| """ | |
| with open(fp) as rf: | |
| sig = rf.read(3) | |
| return sig == "\x1f\x8b\x08" | |
| def extract(fn): | |
| if _is_gzipped(fn): | |
| print 'Extracting: %s...' % fn | |
| gunzip(fn) | |
| elif zipfile.is_zipfile(fn): | |
| unzip(fn) | |
| def dir_iter(p): | |
| for root, dirs, files in os.walk(p): | |
| for f in files: | |
| yield path.join(root, f) | |
| if __name__ == "__main__": | |
| argv = sys.argv[1:] | |
| if not len(argv): | |
| print 'Usage: ginr <path1> <path2> ...' | |
| sys.exit(1) | |
| for p in argv: | |
| if not path.exists(p): | |
| print '%s does not exist!' % p | |
| sys.exit(1) | |
| for p in argv: | |
| if path.isfile(p): | |
| extract(p) | |
| elif path.isdir(p): | |
| for f in dir_iter(p): | |
| extract(f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment