码迷,mamicode.com
首页 > 编程语言 > 详细

python 解压 zip 文件

时间:2019-08-13 00:01:26      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:path   try   print   file   and   pytho   python   port   etc   

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()

python 解压 zip 文件

标签:path   try   print   file   and   pytho   python   port   etc   

原文地址:https://www.cnblogs.com/mlover/p/11337359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!