我一直在使用它,並取得了很多成功。
import fnmatch
import functools
import itertools
import os
# Remove the annotations if you're not on Python3
def find_files(dir_path: str=None, patterns: [str]=None) -> [str]:
"""
Returns a generator yielding files matching the given patterns
:type dir_path: str
:type patterns: [str]
:rtype : [str]
:param dir_path: Directory to search for files/directories under. Defaults to current dir.
:param patterns: Patterns of files to search for. Defaults to ["*"]. Example: ["*.json", "*.xml"]
"""
path = dir_path or "."
path_patterns = patterns or ["*"]
for root_dir, dir_names, file_names in os.walk(path):
filter_partial = functools.partial(fnmatch.filter, file_names)
for file_name in itertools.chain(*map(filter_partial, path_patterns)):
yield os.path.join(root_dir, file_name)
實例:
for f in find_files(test_directory):
print(f)
收率:
.\test.json
.\test.xml
.\test.ini
.\test_helpers.py
.\__init__.py
測試使用多種模式:
for f in find_files(test_directory, ["*.xml", "*.json", "*.ini"]):
print(f)
收率:
.\test.json
.\test.xml
.\test.ini
應該是好的,但一個'tuple'會在這裏更好的(挑剔!)'( 'JPG', 'JPEG', 'GIF', 'PNG')'。 – user225312 2011-03-18 12:12:18
@A A:爲什麼在這種情況下元組更好? – tyrondis 2011-03-18 12:16:37