这是我所拥有的:

glob(os.path.join('src','*.c'))

但是我想搜索src的子文件夹。这样做是可行的:

glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))

但这显然是有限和笨拙的。


当前回答

我修改了这篇文章最上面的答案。最近创建了这个脚本,它将循环遍历给定目录(searchdir)中的所有文件和它下面的子目录…并打印文件名、根目录、修改/创建日期和大小。

希望这能帮助到某人…他们可以遍历目录,得到fileinfo。

import time
import fnmatch
import os

def fileinfo(file):
    filename = os.path.basename(file)
    rootdir = os.path.dirname(file)
    lastmod = time.ctime(os.path.getmtime(file))
    creation = time.ctime(os.path.getctime(file))
    filesize = os.path.getsize(file)

    print "%s**\t%s\t%s\t%s\t%s" % (rootdir, filename, lastmod, creation, filesize)

searchdir = r'D:\Your\Directory\Root'
matches = []

for root, dirnames, filenames in os.walk(searchdir):
    ##  for filename in fnmatch.filter(filenames, '*.c'):
    for filename in filenames:
        ##      matches.append(os.path.join(root, filename))
        ##print matches
        fileinfo(os.path.join(root, filename))

其他回答

对于python >= 3.5,可以使用**,递归=True:

import glob
for f in glob.glob('/path/**/*.c', recursive=True):
    print(f)

如果递归为True(默认为False),模式**将匹配任何文件和零 或者更多的目录和子目录。如果模式后面跟着 一个操作系统。Sep,只有目录和子目录匹配。


Python 3演示

这是Python 2.7上的一个工作代码。作为devops工作的一部分,我被要求编写一个脚本来移动标有live-appName的配置文件。属性到appName.properties。可能还有其他扩展文件,比如live-appName.xml。

下面是一个工作代码,它查找给定目录中的文件(嵌套级别),然后将其重命名(移动)到所需的文件名

def flipProperties(searchDir):
   print "Flipping properties to point to live DB"
   for root, dirnames, filenames in os.walk(searchDir):
      for filename in fnmatch.filter(filenames, 'live-*.*'):
        targetFileName = os.path.join(root, filename.split("live-")[1])
        print "File "+ os.path.join(root, filename) + "will be moved to " + targetFileName
        shutil.move(os.path.join(root, filename), targetFileName)

此函数从主脚本调用

flipProperties(searchDir)

希望这能帮助有类似问题的人。

或者使用列表推导式:

 >>> base = r"c:\User\xtofl"
 >>> binfiles = [ os.path.join(base,f) 
            for base, _, files in os.walk(root) 
            for f in files if f.endswith(".jpg") ] 

Johan和Bruno就上述最低要求提供了出色的解决方案。我刚刚发布了Formic,它实现了Ant FileSet和glob,可以处理这种情况和更复杂的场景。您的需求的实现是:

import formic
fileset = formic.FileSet(include="/src/**/*.c")
for file_name in fileset.qualified_files():
    print file_name

简化版的Johan Dahlin的回答,没有fnmatch。

import os

matches = []
for root, dirnames, filenames in os.walk('src'):
  matches += [os.path.join(root, f) for f in filenames if f[-2:] == '.c']