在实际数据中,经常会有压缩包套压缩包的情况,并且有可能出现“zip”压缩包下面套“tar”的可能。
你可以运行后面的代码,来完成自动解压。代码会不断检查folder_a_path 文件夹下是否还有压缩包。目前支持zip、rar、tar、7z等四种格式的压缩文件。
你需要使用pycharm等工具,将zipfile源码中的“cp437”改成“gbk”,不然解压中文时会出乱码。共有两处需要修改的zipfile源码,修改后的结果如下:
if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800:
# UTF-8 filename
fname_str = fname.decode("utf-8")
else:
fname_str = fname.decode("gbk")
if flags & 0x800:
# UTF-8 file names extension
filename = filename.decode('utf-8')
else:
# Historical ZIP filename encoding
filename = filename.decode('gbk')
完整的代码代码如下:
import os
import tarfile
import patoolib
import zipfile
import py7zr
def extract_archive(archive_path, extract_path):
"""
解压缩指定路径的压缩包到指定目录。
"""
if archive_path.endswith(".zip"):
with zipfile.ZipFile(archive_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
elif archive_path.endswith(".tar"):
with tarfile.open(archive_path, 'r') as tar_ref:
tar_ref.extractall(extract_path)
elif archive_path.endswith(".7z"):
with py7zr.SevenZipFile(archive_path, mode='r') as sz_ref:
sz_ref.extractall(extract_path)
elif archive_path.endswith(".rar"):
patoolib.extract_archive(archive_path,outdir=extract_path)
def extract_all_archives(folder_path):
"""
解压文件夹中的所有压缩包,直到文件夹中没有压缩包为止。
"""
flag=False
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
if file_path.endswith((".zip", ".tar", ".7z", ".rar")):
temp_extract_path = os.path.join(root, file_path[0:file_path.rindex(".")])
if not os.path.exists(temp_extract_path):
print(f"【发现压缩包】{file_path}")
flag=True
os.makedirs(temp_extract_path,exist_ok=True)
extract_archive(file_path, temp_extract_path)
return flag
if __name__=="__main__":
"""
直接处理文件夹,多次执行主函数,直至没有输出为止
"""
folder_a_path = r'C:\xxx\xxx'
contains_unzip_file=True
while contains_unzip_file:
contains_unzip_file=extract_all_archives(folder_a_path)