List 仅从子目录获取文件

List 仅从子目录获取文件,list,python-3.x,dictionary,os.walk,List,Python 3.x,Dictionary,Os.walk,假设我的文件结构: First_Folder |____Second_Folder |___file1.txt |____Third_Folder |___file2.txt 使用os.walk() 输出: File not found. File found! File found! 如何让os.walk()仅查找子目录、第二个\u文件夹和第三个\u文件夹中的文件?正确的结果应该是: File found! File found! 我认为os.walk中没有这样的选项

假设我的文件结构:

First_Folder
|____Second_Folder
     |___file1.txt
|____Third_Folder
     |___file2.txt
使用os.walk()

输出:

File not found.
File found!
File found!
如何让os.walk()仅查找子目录、第二个\u文件夹和第三个\u文件夹中的文件?正确的结果应该是:

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文件),则可以使用:


我阅读了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.')
import glob
# matches *.txt files in subdirectories of "First_Folder"
files = glob.glob('First_Folder/*/*.txt')