python递归解压压缩文件

前言

工作中经常处理工单日志,每次都要手动解压,非常不方便,因此写了一个脚本,用于一键解压。

一、环境

python 3.8.0
三方库:
import zipfile
import py7zr
import rarfile
import tarfile

二、源码

如下,直接贴出代码和注释

import os
import zipfile
import py7zr
import rarfile
import tarfile

unziperr_flag = 0

def unzip_path(dirpath,filepath):
    global unziperr_flag
    ret = 0
    if zipfile.is_zipfile(filepath):
        with zipfile.ZipFile(filepath, 'r') as f:
            ret = 1
            try:
                f.extractall(dirpath)
            except:
                unziperr_flag = 0
                print("zip fail!", filepath)
    elif py7zr.is_7zfile(filepath):
        with py7zr.SevenZipFile(filepath, 'r') as f:
            ret = 1
            try:
                f.extractall(dirpath)
            except:
                unziperr_flag = 0
                print("7z fail!", filepath)
    elif rarfile.is_rarfile(filepath):
        with rarfile.RarFile(filepath, 'r') as f:
            ret = 1
            try:
                f.extractall(dirpath)
            except:
                unziperr_flag = 0
                print("rar fail!", filepath)
    elif tarfile.is_tarfile(filepath):
        with tarfile.open(filepath, 'r') as f:
            ret = 1
            try:
                f.extractall(dirpath)
            except:
                print("tar fail!", filepath)
    if ret:
        os.remove(filepath)
        #print("ret = ", ret, filepath)
    return ret

def unzip_file(root_path):
    if zipfile.is_zipfile(root_path):
        with zipfile.ZipFile(root_path, 'r') as zf:
            dirname = os.path.splitext(root_path)[0].rsplit(".", 1)[0]  # 获取压缩文件名
            try:
                os.makedirs(dirname) 
            except:
                print("\n")
            zf.extractall(dirname)
    elif py7zr.is_7zfile(root_path):
        with py7zr.SevenZipFile(root_path, 'r') as szf:
            dirname = os.path.splitext(root_path)[0].rsplit(".", 1)[0]  # 获取压缩文件名
            try:
                os.makedirs(dirname)  
            except:
                print("\n")
            szf.extractall(dirname)
    elif rarfile.is_rarfile(root_path):
        with rarfile.RarFile(root_path, 'r') as rf:
            dirname = os.path.splitext(root_path)[0].rsplit(".", 1)[0]  # 获取压缩文件名
            try:
                os.makedirs(dirname) 
            except:
                print("\n")
            rf.extractall(dirname)
    elif tarfile.is_tarfile(root_path):
        with tarfile.open(root_path, 'r') as tf:
            dirname = os.path.splitext(root_path)[0].rsplit(".", 1)[0]  # 获取压缩文件名
            try:
                os.makedirs(dirname) 
            except:
                print("\n")
            tf.extractall(dirname)
    elif root_path.endswith('.gz'):
        with gzip.open(root_path, 'rb') as gz:
            with open(os.path.splitext(root_path)[0], 'wb') as f:
                f.write(gz.read())
    return 1

def extract_all_archive_files(root_dir):
    ret = 0
    # 判断是路径还是文件
    if os.path.isdir(root_dir):
        for dirpath, dirnames, filenames in os.walk(root_dir):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                ret += unzip_path(dirpath, filepath)
    elif os.path.isfile(root_dir):
        ret += unzip_file(root_dir)
        root_dir = root_dir.rsplit(".", 1)[0]
    else:
        print("输入的路径不是有效的文件夹或者压缩文件")
    return ret, root_dir


if __name__ == '__main__':
    print(">-------------------------------------------------------------------------------------------------<")
    print("---author:             lxjswd--------------------------------------------------")
    print("---complete date:       2023-6-17------------------------------------------------")
    print("---last change date:    2023-9-8-------------------------------------------------")
    print("---note:                you could decompression zip、7z 、rar、tar、gz files------")
    print("---9.8更新说明:增加解压失败异常处理------------------------------------------------")
    print(">-------------------------------------------------------------------------------------------------<\n\n")
    while 1:
        read_path = input("please input unzip path(输入q退出):")
        if read_path == 'q':
            print(">-----------------------------------------<")
            print(">----------------good bye-----------------<")
            print(">-----------------------------------------<\n\n\n\n\n")
            break
        print("read_path : ", read_path)
        flag = 1
        num = 0
        unziperr_flag = 1
        while 1:
            num += 1
            print("unzip times ", num)
            flag, read_path = extract_all_archive_files(read_path)
            if flag == 0 & unziperr_flag == 1:
                print(">-------------------------------------------------------------------------------------------------<")
                print("unzip succesful!")
                break
            elif flag == 0 & unziperr_flag == 0:
                print(">!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<")
                print("----------------------------------error !!! something unzip err!-----------------------------------\n\n")
                break

三、注意事项

请添加图片描述

在运行脚本后,可以输入单个压缩文件路径如D:\Desk\test\test.zip,也可以输入直接压缩文件所在文件夹路径,如D:\Desk\test

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 `java.util.zip` 包中的 `ZipEntry` 和 `ZipInputStream` 类来递归解压 ZIP 文件。以下是一个示例代码: ```java import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.io.InputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.File; public class UnzipRecursive { public static void main(String[] args) { String zipFilePath = "/path/to/your/file.zip"; String destDirectory = "/path/to/your/destination/directory"; unzipRecursive(zipFilePath, destDirectory); } public static void unzipRecursive(String zipFilePath, String destDirectory) { byte[] buffer = new byte[1024]; try { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zis.getNextEntry(); while (entry != null) { String fileName = entry.getName(); File newFile = new File(destDirectory + File.separator + fileName); if (entry.isDirectory()) { newFile.mkdirs(); unzipRecursive(zipFilePath, newFile.getAbsolutePath()); } else { FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } entry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的代码中,`unzipRecursive` 方法接受 ZIP 文件路径和目标目录路径作为参数,并使用 `FileInputStream` 和 `ZipInputStream` 从 ZIP 文件中读取并解压文件。如果 ZIP 文件中有一个目录,它会递归地调用 `unzipRecursive` 方法来创建目录并解压包含在目录中的文件。如果 ZIP 文件中有一个文件,它将创建一个新文件并将其解压到目标目录中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值