如何使用 os.walk (或任何其他方式)进行搜索,以便我可以在根目录下具有特定模式的目录下找到具有特定名称的文件
我的意思是,如果我有一个目录 d:\installedApps,在该目录下有 a.ear、b.ear、... x.ear、y.ear、z.ear 目录以及其他目录level,我想只在根目录下的*.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
最佳答案
我强烈建议您查看这个答案。有三种不同的解决方案,但#1 似乎最准确地匹配您想要做的事情。
Find all files in a directory with extension .txt in Python
编辑我刚刚找到了一些关于可以完成这项工作的 glob 类的更多信息。
来自 Python 文档
glob.glob(pathname)
Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like
/usr/src/Python-1.5/Makefile
) or relative (like../../Tools/*/*.gif
), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).
所以你可以做一些类似的事情:
def getFiles(path):
answer = []
endPaths = glob.glob(path + "web*.xml")
answer += endPaths
if len(glob.glob(path + "*ear/")) > 0:
answer += getFiles(path + "*ear/")
return answer
filepaths = getFiles("./")
print(filepaths
)
我实际上测试了这个,它在我认为按照您想要的方式设置的目录中运行得非常好。
关于Python 在特定目录模式中搜索文件名模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20353989/