这是我所拥有的:

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 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)

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

刚刚做了这个..它将以分层的方式打印文件和目录

但我没有使用fnmatch或walk

#!/usr/bin/python

import os,glob,sys

def dirlist(path, c = 1):

        for i in glob.glob(os.path.join(path, "*")):
                if os.path.isfile(i):
                        filepath, filename = os.path.split(i)
                        print '----' *c + filename

                elif os.path.isdir(i):
                        dirname = os.path.basename(i)
                        print '----' *c + dirname
                        c+=1
                        dirlist(i,c)
                        c-=1


path = os.path.normpath(sys.argv[1])
print(os.path.basename(path))
dirlist(path)

如果这可能会引起任何人的兴趣,我已经介绍了前三种建议的方法。 我在globbed文件夹中有大约500K个文件(总共),并且有2K个文件符合所需的模式。

下面是(非常基本的)代码

import glob
import json
import fnmatch
import os
from pathlib import Path
from time import time


def find_files_iglob():
    return glob.iglob("./data/**/data.json", recursive=True)


def find_files_oswalk():
    for root, dirnames, filenames in os.walk('data'):
        for filename in fnmatch.filter(filenames, 'data.json'):
            yield os.path.join(root, filename)

def find_files_rglob():
    return Path('data').rglob('data.json')

t0 = time()
for f in find_files_oswalk(): pass    
t1 = time()
for f in find_files_rglob(): pass
t2 = time()
for f in find_files_iglob(): pass 
t3 = time()
print(t1-t0, t2-t1, t3-t2)

我得到的结果是: os_walk: ~ 3.6秒 rglob ~ 14.5秒 iglob: ~ 16.9秒

平台:Ubuntu 16.04, x86_64(核心i7),

除了建议的答案,你还可以用一些惰性生成和列表理解魔法来做到这一点:

import os, glob, itertools

results = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.c'))
                                               for root, dirs, files in os.walk('src'))

for f in results: print(f)

除了适合一行并避免内存中不必要的列表之外,这还有一个很好的副作用,你可以以类似于**操作符的方式使用它,例如,你可以使用os.path。Join (root, 'some/path/*.c')以获取SRC所有子目录下具有此结构的所有。c文件。

我需要一个python 2的解决方案。在大目录上快速工作的X。 我得出了这个结论:

import subprocess
foundfiles= subprocess.check_output("ls src/*.c src/**/*.c", shell=True)
for foundfile in foundfiles.splitlines():
    print foundfile

注意,您可能需要一些异常处理,以防ls找不到任何匹配的文件。