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 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有