ayuLiao
11/6/2018 - 6:09 AM

python解压zip与tar.gz

python解压zip与tar.gz

import zipfile
import tarfile

# 将path指定的压缩文件解压到target_path目录下
def un_zip(path, target_path):
    '''
    Decompression file to target path,
    able decompression zip file and tar.gz file
    '''
    if zipfile.is_zipfile(path): # zip
        zip_file = zipfile.ZipFile(path)
        for file in zip_file.namelist():
            zip_file.extract(file, target_path)
        zip_file.close()

    if tarfile.is_tarfile(path): # tar.gz
        tar = tarfile.open(path, "r:gz")
        for file_name in tar.getnames():
            tar.extract(file_name, target_path)
        tar.close()
    return target_path