Nad*_*mli 212
os.walk就是答案,这将找到第一场比赛:
import os
def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)
这将找到所有匹配:
def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result
这将匹配一个模式:
import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result
find('*.txt', '/path/to/dir')
Ken*_*yon 23
在 Python 3.4 或更高版本中,您可以使用 pathlib 进行递归通配:
>>> import pathlib
>>> sorted(pathlib.Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]
参考:https : //docs.python.org/3/library/pathlib.html#pathlib.Path.glob
在 Python 3.5 或更新版本中,您还可以像这样进行递归通配符:
>>> import glob
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
参考:https : //docs.python.org/3/library/glob.html#glob.glob
kga*_*dek 22
我os.walk在一个更大的目录上使用了一个版本,时间大约为3.5秒.我尝试了两个没有很大改进的随机解决方案,然后做了:
paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()]
虽然只有POSIX,但我得到了0.25秒.
由此,我相信完全可能以独立于平台的方式优化整个搜索,但这是我停止研究的地方.
如果你在 Ubuntu 上使用 Python 并且你只希望它在 Ubuntu 上工作,一个明显更快的方法是locate像这样使用终端的程序。
import subprocess
def find_files(file_name):
    command = ['locate', file_name]
    output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
    output = output.decode()
    search_results = output.split('\n')
    return search_results
search_results是list绝对文件路径。这比上述方法快 10,000 倍,对于我所做的一次搜索,它的速度提高了约 72,000 倍。