租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

如何用python递归解压所有文件,python中递归函数的编写方法

发布时间:2023-10-27 00:50:07

如何用python递归解压所有文件

要用Python递归解压所有文件,你可使用zipfile模块来操作紧缩文件。下面是一个使用递归的示例代码:

import os
import zipfile

def unzip_all_files(directory):
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        if os.path.isfile(item_path) and item.endswith('.zip'):
            # 打开紧缩文件
            with zipfile.ZipFile(item_path, 'r') as zip_ref:
                # 解压文件到当前目录
                zip_ref.extractall(directory)
            # 删除紧缩文件
            os.remove(item_path)
        elif os.path.isdir(item_path):
            # 递归调用解压函数
            unzip_all_files(item_path)

# 指定要解压的目录
directory_to_unzip = 'path/to/directory'
unzip_all_files(directory_to_unzip)

在上面的代码中,首先定义了一个unzip_all_files函数,该函数接受一个目录路径作为参数。然后,遍历目录中的所有项目,如果是一个紧缩文件(以.zip结尾),将其解压到当前目录,并删除原始紧缩文件。如果是一个子目录,则递归调用unzip_all_files函数以解压其中的文件。最后,指定要解紧缩的目录,并调用unzip_all_files函数来开始解压。