python循环遍历文件操作

#!\urs\bin\env python
#encoding:utf-8       #设置编码方式  
import os
import re
class loop_file:
    def __init__(self, root_dir, short_exclude=[], long_exclude=[], file_extend=[]):
        self.root_dir = root_dir
        self.short_exclude = short_exclude
        self.long_exclude = long_exclude
        self.file_extend = file_extend
    
    def __del__(self):
        pass
    
    def start(self, func):
        self.func = func
        return self.loop_file(self.root_dir)
    
    def loop_file(self, root_dir):
        t_sum = []
        sub_gen = os.listdir(root_dir)
        for sub in sub_gen:
            is_exclude = False
            for extends in self.short_exclude:  ##在不检查文件、目录范围中
                if extends in sub:              ##包含特定内容
                    is_exclude = True
                    break
                if re.search(extends, sub):     ##匹配指定正则
                    is_exclude = True
                    break                    
            if is_exclude:
                continue            
            abs_path = os.path.join(root_dir, sub)
            is_exclude = False
            for exclude in self.long_exclude:
                if exclude == abs_path[-len(exclude):]:
                    is_exclude = True
                    break
            if is_exclude:
                continue
            if os.path.isdir(abs_path):
                t_sum.extend(self.loop_file(abs_path))
            elif os.path.isfile(abs_path):            
                if not "." + abs_path.rsplit(".", 1)[1] in self.file_extend:  ##不在后缀名 检查范围中
                    continue
                t_sum.append(self.func(abs_path))
        return t_sum
    
if '__main__'==__name__:
    root_dir = r'D:\harness\newshoppingcart\testcase\promo\single_promo'
    short_exclude = ['.svn', '.*_new.rb']     ###不包含检查的短目录、文件
    long_exclude = []                         ###不包含检查的长目录、文件
    file_extend = ['.rb']                     ###包含检查的文件类型
    lf = loop_file(root_dir, short_exclude, long_exclude, file_extend)
    for f in lf.start(lambda f: f):
        print f

给定一个主目录,循环其下特定过滤规则的文件,并传给自定义的处理函数,最后返回每一个自定义函数返回的结果内容的列表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上帝De助手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值