python 解压各种类型的压缩包&遍历文件夹文件优化

本文介绍使用Python进行文件解压及遍历文件夹的高效方法,利用glob模块和os模块实现对多种压缩格式(如.zip、.rar等)的解压,并遍历包含子文件夹的目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     用python遍历文件夹的时候,由于文件夹会包括文件夹的情况,很多人刚开始会想到的是递归遍历,于是去网上搜索遍历的方法,结果出现很大一串代码,递归调用,结果试了半天还晕头转向,还需要加以验证,其实python有一个十分快捷的方法,不得不说这就是越来越多的人开始用python的原因

    

     path1 = glob.glob(unzip + '\**',recursive=True)   #unzip指的是你需要遍历的文件夹

     print (path1)

     在用python解压缩包的时候,有两种方法,一种是根据不同的压缩包类型,调python中不同的库。比如说解压zip类型压缩包,需要用到unzip,解压tar类型压缩包,又需要调用其他的库,这样做不好。另外一种方法是下载一个7z软件,找到exe所在路径,然后在python中调用os模块,输入对应的7z命令,就可以解决众多类型的压缩包。

     解压命令为:

cmd = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -oe:/测试解压/new *.mp4 -r'.format(name)
            os.popen(cmd)

     可以参照这篇文章:https://www.cnblogs.com/greatfish/p/7208957.html

     近期遇到一个需求就是需要遍历某个目录下的所有文件,有个前提,这个目录下不会有文件夹,要么是文件,要么是压缩包。如果是压缩包需要解压,压缩包中也会有文件夹,遍历该目录下的所有文件,找到包含了关键字的文件路径,如果条件吻合,有需要的人可以直接copy,代码如下

import os
import glob
import time

def getFileAtt(folder_name,contains_name):
    print(folder_name)
    os.chdir(folder_name)
    file_names = os.listdir("./")
    file_att_list = []
    for name in file_names:
        print("是不是文件:", os.path.isfile(name))
        if os.path.isfile(name):
            name = os.path.abspath(name)
            # 返回一个元组,元组第二个元素是扩展名
            if os.path.splitext(name)[1] == ".zip":
                unzip = os.path.splitext(name)[0]
                order = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -o'+ folder_name + ' -r'
                print(order)
                cmd = order.format(name)
                os.popen(cmd)
                #不设置延时会导致还没有解压完,就开始去找文件,导致找到文件错误
                time.sleep(1)
                path1 = glob.glob(unzip + '\**',recursive=True)
                #print (path1)
                file_att_list.append(path1)
                

            elif os.path.splitext(name)[1] == ".rar":
                unzip = os.path.splitext(name)[0]
                order = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -o'+ folder_name + ' -r'
                print(order)
                cmd = order.format(name)
                os.popen(cmd)
                time.sleep(1)
                path1 = glob.glob(unzip + '\**',recursive=True)
                #print (path1)
                file_att_list.append(path1)
            
            elif os.path.splitext(name)[1] == ".7z":
                unzip = os.path.splitext(name)[0]
                order = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -o'+ folder_name + ' -r'
                cmd = order.format(name)
                os.popen(cmd)
                time.sleep(1)
                path1 = glob.glob(unzip + '\**',recursive=True)
                #print (path1)
                file_att_list.append(path1)
            
            elif os.path.splitext(name)[1] == ".gzip":
                unzip = os.path.splitext(name)[0]
                order = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -o'+ folder_name + ' -r'
                cmd = order.format(name)
                os.popen(cmd)
                time.sleep(1)
                path1 = glob.glob(unzip + '\**',recursive=True)
                #print (path1)
                file_att_list.append(path1)
            
            elif os.path.splitext(name)[1] == ".tar":
                unzip = os.path.splitext(name)[0]
                order = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -o'+ folder_name + ' -r'
                cmd = order.format(name)
                os.popen(cmd)
                time.sleep(1)
                path1 = glob.glob(unzip + '\**',recursive=True)
                #print (path1)
                file_att_list.append(path1)

            elif os.path.splitext(name)[1] == ".bzip2":
                unzip = os.path.splitext(name)[0]
                order = '\"C:\\Program Files\\7-Zip\\7z.exe\" x \"{0}\" -o'+ folder_name + ' -r'
                cmd = order.format(name)
                os.popen(cmd)
                time.sleep(1)
                path1 = glob.glob(unzip + '\**',recursive=True)
                #print (path1)
                file_att_list.append(path1)
            else:
                #print(name)
                file_att_list.append(name)

    fileAtt = ''

    for att_list in file_att_list:
        if(contains_name in att_list):
            print("*********" + att_list)
            fileAtt = att_list
            break
        for att in att_list:
            if(contains_name in att):
                fileAtt = att
                break
    
    print('最后得到需要路径为:' + fileAtt)
    return fileAtt

getFileAtt('C:/Users/hand_wl/Desktop/unfile','商务采购需求申请书' )

      

根据自己需要加以修改,此文介绍python解压跟python遍历文件夹的两种简便方法~

希望对人有帮助,毕竟刚开始知道这个需要的时候内心是爆炸的。

Python中,你可以使用`os`, `shutil`, 和 `zipfile` 这些内置模块来实现这个功能。下面是一个简单的示例,它会遍历指定目录,如果遇到`.zip` 文件,尝试解压它们: ```python import os import shutil import zipfile def extract_if_zip(directory): for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.zip'): # 检查是否为.zip文件 zip_path = os.path.join(root, file) try: with zipfile.ZipFile(zip_path, 'r') as zipped_file: if zipped_file.testzip() is None: # 如果没有解压错误,则尝试解压 print(f"Found and extracting {zip_path}") out_dir = os.path.join(root, os.path.splitext(file)[0]) # 创建解压后的目录名 os.makedirs(out_dir, exist_ok=True) # 确保目标目录存在 zipped_file.extractall(path=out_dir) # 解压到该目录 except zipfile.BadZipFile: print(f"{zip_path} appears to be a corrupted or encrypted zip file.") except Exception as e: print(f"Error processing {zip_path}: {str(e)}") # 调用函数并传入需要遍历的根目录 extract_if_zip('/path/to/your/directory') ``` 注意,这个脚本仅检查文件名是否以`.zip` 结尾,并假设它是一个标准的未加密的ZIP文件。对于加密的ZIP文件,你需要先解密才能解压,这通常涉及到使用密码,而Python的`zipfile` 模块本身并不提供直接的加密文件支持。如果你知道加密的密码,可以使用`zipfile.PasswordZipFile` 类。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值