用os模块构建文件查找器

探索目录树深度

>>> import os

>>> for t in os.walk('./'):

...     print(t)


#/usr/bin/python
#coding:utf-8

#file_tree.py module containing functions to assist
#in working with directory hierarchies
#Base on the os.walk() function.
#os.walk()返回三元组(当前目录,当前目录下的目录列表,当前目录下的文件列表)
import os,re
import os.path as path

#查找文件
def find_files(pattern,base='.'):
    regex = re.compile(pattern)           #参数pattern接受正则表达式,为了提高效率而编译
    matches = []
    for root,dits,files in os.walk(base):
        for f in files:
            if regex.match(f):            #匹配
                matches.append(path.join(root,f)) #当前目录路经root+文件名f path.join
    return matches

#查找目录
def find_dirs(pattern,base = '.'):
    regex = re.compile(pattern)
    matches = []
    for root,dits,files in os.walk(base):
        for d in dits:
            if regex.match(d):
                matches.append(path.join(root,d))
    return matches

#查找目录和文件
def find_all(pattern ,base = '.'):
    matches = find_dirs(pattern,base)
    matches += find_files(pattern,base)
    return matches

#参数function作用到查找到文件上
def apply_to_files(pattern,function,base = '.'):
    regex = re.compile(pattern)
    errors = []
    for root,dits,files in os.walk(base):
        for f in files:
            if regex.match(f):
                try:function(path.join(root,f))
                except:errors.append(path.join(root,f))
    return errors

if __name__ == "__main__":

    filename = find_files('.*\.txt','TreeRoot')
    print(filename)
    filename = find_all('D1','TreeRoot')
    print(filename)
    apply_to_files('.*\.txt',os.remove,'TreeRoot') #第二个参数传入了os.remove方法(删除文件)
    
注:测试目录TreeRoot 已上传


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值