Unzip the file if file is bzipped = ending with 'bz2
172562
def unzip_file(filename):
    """'"""

    if filename.endswith('bz2'):
        bz2file = bz2.BZ2File(filename)
        fdn, tmpfilepath = tempfile.mkstemp()
        with closing(os.fdopen(fdn, 'wb')) as ofpt:
            try:
                ofpt.write(bz2file.read())
            except IOError:
                import traceback
                traceback.print_exc()
                LOGGER.info("Failed to read bzipped file %s", str(filename))
                os.remove(tmpfilepath)
                return None

        return tmpfilepath

    return None
582443
def unzip_file_to_dir(path_to_zip, output_directory):
    
    z = ZipFile(path_to_zip, 'r')
    z.extractall(output_directory)
    z.close()
564063
function unzip(file, callback) {
    var metafile = metapath(file);
    // return cached result of unzipped file
    // intentionally sync here to avoid race condition unzipping
    // same file for multiple layers
    try {
        var meta_data = fs.readFileSync(metafile);
        if (meta_data) {
            var meta = JSON.parse(meta_data);
            var dest_file = meta['unzipped_file'];
            if (dest_file && existsSync(dest_file)) {
                if (env == 'development') console.error('[millstone] found previously unzipped file: ' + dest_file);
                return callback(null,dest_file);
            }
        } else {
            if (env == 'development') console.error('[millstone] empty meta file for zipfile: ' + metafile);
        }
    }
    catch (err) {
        if (env == 'development') console.error('[millstone] error opening meta file for zipfile: ' + err.message);
    }
    var zf;
    try {
        zf = new zipfile.ZipFile(file);
    } catch (err) {
        return callback(err);
    }

    if (zf.names.length < 1) {
        return callback(new Error("could not find any valid data in zip archive: '" + file + "'"));
    }

    var remain = zf.names.length;
    var ds_files = _(zf.names).chain()
        .reject(function(name) {
            return (name && (name[0] === '.' || path.basename(name)[0] === '.'));
        })
        .map(function(name) {
            if (!valid_ds_extensions[path.extname(name).toLowerCase()]) return;
            var new_name = path.join(
                path.dirname(file),
                path.basename(file, path.extname(file)) +
                path.extname(name).toLowerCase());
            return {new_name:new_name,original_name:name};
        })
        .uniq()
        .compact()
        .value();

    if (!ds_files || ds_files.length < 1) return callback(new Error("Valid datasource not detected (by extension) in zip: '" + file + "'"));

    var original_name = ds_files[0].original_name;
    var new_name = ds_files[0].new_name;

    var len = Object.keys(ds_files).length;
    if (len > 1) {
        // prefer first .shp
        for (var i=0;i<len;++i) {
            var fname = ds_files[i].original_name;
            if (path.extname(fname) == '.shp') {
                original_name = fname;
                new_name = ds_files[i].new_name;
                break;
            }
        }
        if (env == 'development') {
            console.warn('[millstone] warning: detected more than one file in zip (by ext) that may be valid: ');
            for (var i=0;i<len;++i) {
                console.warn('[millstone]   ' + ds_files[i].original_name);
            }
            console.warn('[millstone] picked: ' + original_name);
        }
    }

    if (!new_name) return callback(new Error("Valid datasource not detected (by extension) in zip: '" + file + "'"));

    if (env == 'development') {
        console.warn('[millstone] renaming ' + original_name + ' to ' + new_name);
    }

    // only unzip files that match our target name
    // naive '(name.indexOf(search_basename) < 0)' does the trick
    // yes this is simplistic, but its better than corrupt data: https://github.com/mapbox/millstone/issues/99
    var search_basename = path.basename(original_name,path.extname(original_name));
    zf.names.forEach(function(name) {
        // Skip directories, hiddens.
        var basename = path.basename(name);
        if (!path.extname(name) || (name.indexOf(search_basename) < 0) || name[0] === '.' || basename[0] === '.') {
            remain--;
            if (!remain) callback(null, new_name);
        } else {
            // We're brutal in our expectations -- don't support nested
            // directories, and rename any file from `arbitraryName.SHP`
            // to `[hash].shp`.
            var dest = path.join(
                path.dirname(file),
                path.basename(file, path.extname(file)) +
                path.extname(name).toLowerCase()
            );
            zf.copyFile(name, dest, function(err) {
                if (err) return callback(err);
                remain--;
                if (!remain) {
                    add_item_to_metafile(metafile,'unzipped_file',new_name,function(err) {
                        // ignore error from add_item_to_metafile
                        //if (err && env == 'development') console.error('[millstone] ' + err.message);
                        if (err) throw err;
                        callback(null, new_name);
                    });
                }
            });
        }
    });
}
81098
def is_zipfile(filename):
    
    result = False
    try:
        if hasattr(filename, "read"):
            result = _check_zipfile(fp=filename)
        else:
            with open(filename, "rb") as fp:
                result = _check_zipfile(fp)
    except OSError:
        pass
    return result
492873
def __gzip(filename):
		
		zipname = filename + '.gz'
		file_pointer = open(filename,'rb')
		zip_pointer = gzip.open(zipname,'wb')
		zip_pointer.writelines(file_pointer)
		file_pointer.close()
		zip_pointer.close()
		return zipname
1202061
def is_zip_file(models):
    
    '''
    ext = os.path.splitext(models[0])[1]
    return (len(models) == 1) and (ext == '.zip')
453713
def _check_gzipped_input(in_file, data):
    
    grabix = config_utils.get_program("grabix", data["config"])
    is_bgzip = subprocess.check_output([grabix, "check", in_file])
    if is_bgzip.strip() == "yes":
        return False, False
    else:
        return True, True
1040521
public static boolean isZip(String fileName) {
		if (fileName == null) {
			return false;
		}

		String tl = fileName.toLowerCase();
		for (String element : ZIP_EXTENSIONS) {
			if (tl.endsWith(element)) {
				return true;
			}
		}
		return false;
	}
327316
def pack(name, root, path=None, pack_format='tar', compress='bzip2'):
    '''
    
    '''
    if pack_format == 'tar':
        _tar(name, root, path, compress)
416931
def must_open(filename, mode="r", checkexists=False, skipcheck=False, \
            oappend=False):
    
    if isinstance(filename, list):
        assert "r" in mode

        if filename[0].endswith((".gz", ".bz2")):
            filename = " ".join(filename)  # allow opening multiple gz/bz2 files
        else:
            import fileinput
            return fileinput.input(filename)

    if filename.startswith("s3://"):
        from jcvi.utils.aws import pull_from_s3
        filename = pull_from_s3(filename)

    if filename in ("-", "stdin"):
        assert "r" in mode
        fp = sys.stdin

    elif filename == "stdout":
        assert "w" in mode
        fp = sys.stdout

    elif filename == "stderr":
        assert "w" in mode
        fp = sys.stderr

    elif filename == "tmp" and mode == "w":
        from tempfile import NamedTemporaryFile
        fp = NamedTemporaryFile(delete=False)

    elif filename.endswith(".gz"):
        if 'r' in mode:
            cmd = "gunzip -c {0}".format(filename)
            fp = popen(cmd, debug=False)
        elif 'w' in mode:
            import gzip
            fp = gzip.open(filename, mode)

    elif filename.endswith(".bz2"):
        if 'r' in mode:
            cmd = "bzcat {0}".format(filename)
            fp = popen(cmd, debug=False)
        elif 'w' in mode:
            import bz2
            fp = bz2.BZ2File(filename, mode)

    else:
        if checkexists:
            assert mode == "w"
            overwrite = (not op.exists(filename)) if skipcheck \
                        else check_exists(filename, oappend)
            if overwrite:
                if oappend:
                    fp = open(filename, "a")
                else:
                    fp = open(filename, "w")
            else:
                logging.debug("File `{0}` already exists. Skipped."\
                        .format(filename))
                return None
        else:
            fp = open(filename, mode)

    return fp
228016
def extract_xz(archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    return _extract(archive, compression, cmd, 'xz', verbosity, outdir)
1354582
def is_valid_filename(filename, return_ext=False):
    """"""
    ext = Path(filename).suffixes

    if len(ext) > 2:
        logg.warn('Your filename has more than two extensions: {}.\n'
                  'Only considering the two last: {}.'.format(ext, ext[-2:]))
        ext = ext[-2:]

    # cases for gzipped/bzipped text files
    if len(ext) == 2 and ext[0][1:] in text_exts and ext[1][1:] in ('gz', 'bz2'):
        return ext[0][1:] if return_ext else True
    elif ext and ext[-1][1:] in avail_exts:
        return ext[-1][1:] if return_ext else True
    elif ''.join(ext) == '.soft.gz':
        return 'soft.gz' if return_ext else True
    elif ''.join(ext) == '.mtx.gz':
        return 'mtx.gz' if return_ext else True
    else:
        if return_ext:
            raise ValueError('"{}" does not end on a valid extension.\n'
                             'Please, provide one of the available extensions.\n{}\n'
                             'Text files with .gz and .bz2 extensions are also supported.'
                             .format(filename, avail_exts))
        else:
            return False
626873
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
        
        if len(mode) > 1 or mode not in "rw":
            raise ValueError("mode must be 'r' or 'w'.")

        try:
            import bz2
        except ImportError:
            raise CompressionError("bz2 module is not available")

        if fileobj is not None:
            fileobj = _BZ2Proxy(fileobj, mode)
        else:
            fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)

        try:
            t = cls.taropen(name, mode, fileobj, **kwargs)
        except (IOError, EOFError):
            fileobj.close()
            raise ReadError("not a bzip2 file")
        t._extfileobj = False
        return t
528169
def bin_open(fname: str):
    
    if fname.endswith(".gz"):
        return gzip.open(fname, "rb")
    return open(fname, "rb")
427748
def unzip_data():
    
    with ZipFile(os.path.join(CACHE_FOLDER, CACHE_ZIP), 'r') as zf:
        zf.extractall(path=CACHE_FOLDER)
845327
def _open_file(self, mode, encoding=None):
        
        if self._filename[-4:] == '.bz2':
            self._file = bz2.open(self._filename, mode=mode, encoding=encoding)
        else:
            self._file = open(self._filename, mode=mode, encoding=encoding)
664501
def open_any(filename):
    
    if filename.endswith(".gz"):
        return gzip.open

    if filename.endswith(".bz2"):
        return bz2.BZ2File

    return open