仅从子目录获取文件

Get Files from Subdirectory Only

假设我的文件结构:

First_Folder
|____Second_Folder
     |___file1.txt
|____Third_Folder
     |___file2.txt

使用os.walk()

for r, d, f in os.walk ('First_Folder'):
    if f:
        print ('File found!')
    else:
        print ('File not found.')

输出:

File not found.
File found!
File found!

如何告诉 os.walk () 只 在子目录 Second_Folder 和 Third_Folder 中查找文件?正确的结果应该是:

File found!
File found!

我认为 os.walk 中没有执行此操作的选项,但您可以自己检查一下:

for r, d, f in os.walk ('First_Folder'):
    # We only want subdirectories.
    if r == 'First_Folder':
        continue
    if f:
        print ('File found!')
    else:
        print ('File not found.')

或者,如果您只查找具有特定模式的文件(例如所有 .txt 文件),您可以使用 glob:

import glob
# matches *.txt files in subdirectories of "First_Folder"
files = glob.glob('First_Folder/*/*.txt')