python 解壓 zip 文件


python 解壓壓縮包

  • 使用 python 的 zipfile 模塊 對同一目錄下的所有 zip 文件解壓,也可以指定解壓文件名
import os
import sys
import zipfile


def unzip(filename: str):
    try:
        file = zipfile.ZipFile(filename)
        dirname = filename.replace('.zip', '')
        # 如果存在與壓縮包同名文件夾 提示信息並跳過
        if os.path.exists(dirname):
            print(f'{filename} dir has already existed')
            return
        else:
            # 創建文件夾,並解壓
            os.mkdir(dirname)
            file.extractall(dirname)
            file.close()
            # 遞歸修復編碼
            rename(dirname)
    except:
        print(f'{filename} unzip fail')


def rename(pwd: str, filename=''):
    """壓縮包內部文件有中文名, 解壓后出現亂碼,進行恢復"""
    
    path = f'{pwd}/{filename}'
    if os.path.isdir(path):
        for i in os.scandir(path):
            rename(path, i.name)
    newname = filename.encode('cp437').decode('gbk')
    os.rename(path, f'{pwd}/{newname}')


def main():
    """如果指定文件,則解壓目標文件,否則解壓當前目錄下所有文件"""
    
    if len(sys.argv) != 1:
        i: str
        for i in sys.argv:
            if i.endswith('.zip') and os.path.isfile(i):
                unzip(i)
    else:
        for file in os.scandir(os.getcwd()):
            if file.name.endswith('.zip') and file.is_file():
                unzip(file.name)


if __name__ == '__main__':
    main()


免責聲明!

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



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