如何使用os.walk(或任何其他方式)以某种搜索方式搜索,以便我可以在根目录下的特定模式的目录下定位具有特定名称的文件?
我的意思是,如果我有一个目录d:\installedApps,在这个目录下我有a.ear、b.ear、...x.ear、y.ear、z.ear等目录,以及同级别的其他目录,我想仅在根目录下的*.ear子目录中搜索web * .xml 的文件,而不遍历同级别的其他目录,我该怎么做?
我尝试了各种方法(包括使用此站点上的一些其他示例,例如walklevel示例等),但我没有得到想要的结果。
更新:我尝试使用此站点上的walkdepth代码片段,并尝试将其组合在嵌套循环中,但那并不起作用。
以下是我尝试过的代码:
我的意思是,如果我有一个目录d:\installedApps,在这个目录下我有a.ear、b.ear、...x.ear、y.ear、z.ear等目录,以及同级别的其他目录,我想仅在根目录下的*.ear子目录中搜索web * .xml 的文件,而不遍历同级别的其他目录,我该怎么做?
我尝试了各种方法(包括使用此站点上的一些其他示例,例如walklevel示例等),但我没有得到想要的结果。
更新:我尝试使用此站点上的walkdepth代码片段,并尝试将其组合在嵌套循环中,但那并不起作用。
以下是我尝试过的代码:
import os, os.path
import fnmatch
def walk_depth(root, max_depth):
print 'root in walk_depth : ' + root
# some initial setup for getting the depth
root = os.path.normpath(root)
depth_offset = root.count(os.sep) - 1
for root, dirs, files in os.walk(root, topdown=True):
yield root, dirs, files
# get current depth to determine if we need to stop
depth = root.count(os.sep) - depth_offset
if depth >= max_depth:
# modify dirs so we don't go any deeper
dirs[:] = []
for root, dirs, files in walk_depth('D:\installedApps', 5):
for dirname in dirs:
if fnmatch.fnmatch(dirname, '*.ear'):
print 'dirname : ' + dirname
root2 = os.path.normpath(dirname)
for root2, dir2, files2 in walk_depth(root2, 5):
for filename in files2:
if fnmatch.fnmatch(filename, 'webservices.xml'):
print '\tfilename : ' + filename