探索目录树深度
>>> 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 已上传