使用Python3解壓gz、tar、tgz、zip、rar五種格式的壓縮文件例子


使用Python3解壓如下五種壓縮文件:gz、tar、tgz、zip、rar

簡介

gz: 即gzip,通常只能壓縮一個文件。與tar結合起來就可以實現先打包,再壓縮。

tar: linux系統下的打包工具,只打包,不壓縮

tgz:即tar.gz。先用tar打包,然后再用gz壓縮得到的文件

zip: 不同於gzip,雖然使用相似的算法,可以打包壓縮多個文件,不過分別壓縮文件,壓縮率低於tar。

rar:打包壓縮文件,最初用於DOS,基於window操作系統。壓縮率比zip高,但速度慢,隨機訪問的速度也慢。

例子

import gzip
import os
import tarfile , zipfile, rarfile

from library.utils.file import get_filetype
from library.utils.path import make_dir
from library.utils.type_conv import random_str

def uncompress(src_file, dest_dir):
    result = get_filetype(src_file)
    if not result[0] :
        return (False, result[1], '')
    filefmt = result[1]

    result = make_dir(dest_dir)
    if not result :
        return (False, '創建解壓目錄失敗', filefmt)

    if filefmt in ('tgz', 'tar') :
        try :
            tar = tarfile.open(src_file)  
            names = tar.getnames()   
            for name in names:  
                tar.extract(name, dest_dir)  
            tar.close()
        except Exception as e :
            return (False, e, filefmt)
    elif filefmt == 'zip':
        try :
            zip_file = zipfile.ZipFile(src_file)  
            for names in zip_file.namelist():  
                zip_file.extract(names, dest_dir)  
            zip_file.close()  
        except Exception as e :
            return (False, e, filefmt)
    elif filefmt == 'rar' :
        try :
            rar = rarfile.RarFile(src_file)  
            os.chdir(dest_dir)
            rar.extractall()  
            rar.close()  
        except Exception as e :
            return (False, e, filefmt)
    elif filefmt == 'gz' :
        try :

            f_name = dest_dir + '/' + os.path.basename(src_file)
            # 獲取文件的名稱,去掉  
            g_file = gzip.GzipFile(src_file)  
            # 創建gzip對象  
            open(f_name, "w+").write(g_file.read())  
            # gzip對象用read()打開后,寫入open()建立的文件中。  
            g_file.close()  
            # 關閉gzip對象  

            result = get_filetype(src_file)
            if not result[0] :
                new_filefmt = '未知'
            else :
                new_filefmt = result[1]
            return (True, '解壓后的文件格式為:' + new_filefmt, filefmt)
        except Exception as e :
            return (False, e, filefmt)
    else :
        return (False, '文件格式不支持或者不是壓縮文件', filefmt)

    return (True, '', filefmt)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM