python递归解压压缩包zip,tar,rar

python递归解压压缩包zip,tar,rar

  • 目前代码仅实现了zip递归解包,tar,rar解包和zip解包类似,只用换成tarfile,rarfile模块处理即可
# -*- coding: utf-8 -*-
# @Time    : 2020/10/9 21:50
# @Author  : cd
import shutil
import zipfile
import os

recursive_unzip_file = []
def recursive_unzip(path, zfile):
    file_path = path + os.sep + zfile
    # 给解压后的文件生成文件名相同的文件夹
    des_dir = path + os.sep + zfile[:zfile.index('.zip')]
    srcfile = zipfile.ZipFile(file_path)
    for file_name in srcfile.namelist():
        if file_name.endswith('.zip'):
            temp_del_file = os.path.join(des_dir, file_name)
            if temp_del_file not in recursive_unzip_file:
                recursive_unzip_file.append(temp_del_file)
        srcfile.extract(file_name, des_dir)
        if file_name.endswith('.zip'):
            temp_del_file = os.path.join(des_dir, zfile)
            if temp_del_file not in recursive_unzip_file:
                recursive_unzip_file.append(temp_del_file)
            # if zipfile.is_zipfile(filename):
            path = des_dir
            zfile = file_name
            recursive_unzip(path, zfile)


def del_file(file_path):
    """
    删除指定路径下的所有文件和文件夹
    :param file_path: 路径
    :return:
    """
    for del_file_path in file_path:
        if os.path.isfile(del_file_path):
            os.remove(del_file_path)
        elif os.path.isdir(del_file_path):
            shutil.rmtree(del_file_path)


if __name__ == '__main__':
    path = r'F:\code\spider\recursive_unzip'
    zfile = r'recursive_file.zip'
    recursive_unzip_file.append(os.path.join(path, zfile))
    recursive_unzip(path, zfile)
    print(recursive_unzip_file)
    print(len(recursive_unzip_file))
    del_file(recursive_unzip_file)
备注:
  • 解压文件名中文乱
    • 原因是zip包源码没有适配gbk编码

    • 解决方法一:

      • 修改源码,zipfile.py中cp437解码全部换成gbk,源码中只涉及两处用到cp437编码,把这两处编码都修改一下即可,亲测有效
        在这里插入图片描述
    • 解决方法二:

      • 代码适配,思路是把文件名用cp437编码之后再用gbk编码解码,这样也可以解决中文乱码问题,old_name.encode('cp437').decode('gbk')
  • Windows下文件路径太长导致文件操作失败,搜集两个办法,但是我暂时还未处理到这种情况,以下两个方法仅供参考
    • 解决方法一:
      # 缩短路径方法
      import win32api
      path = win32api.GetShortPathName(path)
      
    • 解决方法二:
      在路径之前添加\\?\
      egg:shutil.copyfile \\?\"+ copy_file,dest_file)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值