阅读AI方面的源代码总是遇到glob.glob()的函数获取相关路径,也算是一个提供便利的轮子了。
具体官方的接口文档已经解释得很清楚了。
附上yolov5的使用例子:
def check_file(file):
# Search for file if not found
if os.path.isfile(file) or file == '':
return file
else:
files = glob.glob('./**/' + file, recursive=True) # find file
assert len(files), 'File Not Found: %s' % file # assert file was found
assert len(files) == 1, "Multiple files match '%s', specify exact path: %s" % (file, files) # assert unique
return files[0] # return file
很显然这个函数是检测文件是否存在且该目录及其子目录下有且只有一个该文件,并返回该文件路径。这里的"**"表示的是可递归查找,此时的glob的参数recursive需要设置成True。其他的表达方式就是普通的正则表达式了。
使用**进行递归,官方说了:
Note Using the “**” pattern in large directory trees may consume an inordinate amount of time.