python 文件壓縮及解壓

文件壓縮app

import os
import zipfile
def zip_dir(dirname,zipfilename):
    """
    | ##@函數目的: 壓縮指定目錄爲zip文件
    | ##@參數說明:dirname爲指定的目錄,zipfilename爲壓縮後的zip文件路徑
    | ##@返回值:無
    | ##@函數邏輯:
    """
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else :
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
                print(os.path.join(root, name))
    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        zf.write(tar,arcname)
    zf.close()

解壓文件:函數

def unzip_file(zipfilename, unziptodir):
    """
    | ##@函數目的: 解壓zip文件到指定目錄
    | ##@參數說明:zipfilename爲zip文件路徑,unziptodir爲解壓文件後的文件目錄
    | ##@返回值:無
    | ##@函數邏輯:
    """
    if not os.path.exists(unziptodir):
        os.mkdir(unziptodir)
    zfobj = zipfile.ZipFile(zipfilename)
    for name in zfobj.namelist():
        name = name.replace('\\','/')

        if name.endswith('/'):
            p = os.path.join(unziptodir, name[:-1])
            if os.path.exists(p):
                # 若是文件夾存在,就刪除之:避免有新更新沒法複製
                shutil.rmtree(p)
            os.mkdir(p)
        else:
            ext_filename = os.path.join(unziptodir, name)
            ext_dir= os.path.dirname(ext_filename)
            ext_dir = ext_dir.replace('\\','/')
            if not os.path.exists(ext_dir):
                os.mkdir(ext_dir)
            outfile = open(ext_filename, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()
相關文章
相關標籤/搜索