如果文件不存在使用 os.walk

if file don't exist using os.walk

有没有一种简单的方法来检查一个文件是否存在于整个文件夹结构中而无需循环? (需要使用os.walk)

"if file exist in in my_dir and its sub directories"
    for root, dirs, files in os.walk(my_dir):
       # do stuff
else:
    print("file does not exist")

使用glob.glob如下:

import glob

fname = 'some_file.txt'
my_dir = '/some_dir' # can also be a relative path
files = glob.glob(f'{my_dir}/**/{fname}', recursive=True)
if files: # list of files that match
    # do something

glob.glob 现在将在目录 my_dir 或其任何子目录中查找文件 some_file.txt