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
编码,把这两处编码都修改一下即可,亲测有效
- 修改源码,zipfile.py中
-
解决方法二:
- 代码适配,思路是把文件名用
cp437
编码之后再用gbk
编码解码,这样也可以解决中文乱码问题,old_name.encode('cp437').decode('gbk')
- 代码适配,思路是把文件名用
-
- Windows下文件路径太长导致文件操作失败,搜集两个办法,但是我暂时还未处理到这种情况,以下两个方法仅供参考
- 解决方法一:
# 缩短路径方法 import win32api path = win32api.GetShortPathName(path)
- 解决方法二:
在路径之前添加\\?\
egg:shutil.copyfile \\?\”+ copy_file,dest_file)
- 解决方法一:
版权声明:本文为weixin_42337937原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。