前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python递归解压压缩包zip,tar,rar

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

作者头像
用户7886150
修改2021-01-22 10:45:42
1.7K0
修改2021-01-22 10:45:42
举报
文章被收录于专栏:bit哲学院

参考链接: Python递归

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)

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档