https://docs.python.org/3.6/library/glob.html
大多Python函數有着長且具有描述性的名字。但是命名為glob()的函數你可能不知道它是干什么的除非你從別處已經熟悉它了。
它像是一個更強大版本的listdir()函數。它可以讓你通過使用模式匹配來搜索文件。
import glob # get all py files files = glob.glob('*.py') print files # Output # ['arg.py', 'g.py', 'shut.py', 'test.py']
你可以像下面這樣查找多個文件類型:
import itertools as it, glob def multiple_file_types(*patterns): return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements print filename # output #=========# # test.txt # arg.py # g.py # shut.py # test.py
如果你想得到每個文件的絕對路徑,你可以在返回值上調用realpath()函數:
import itertools as it, glob, os def multiple_file_types(*patterns): return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements realpath = os.path.realpath(filename) print realpath # output #=========# # C:\xxx\pyfunc\test.txt # C:\xxx\pyfunc\arg.py # C:\xxx\pyfunc\g.py # C:\xxx\pyfunc\shut.py # C:\xxx\pyfunc\test.py