首页 > 解决方案 > 遍历python中的目录

问题描述

我想编写一个代码来分别查找子目录中的所有文件,然后为每个子目录执行一个操作,然后继续进行..我想出了下面的代码,但这会遍历目录中的所有文件,但我需要抓取特定子目录中的所有文件..

for root, dirs, files in os.walk(train_path_healthy):
    for filename in files:
        if (os.path.splitext(os.path.join(root, filename))[1] == ".png"):

有人可以帮我在python中如何做到这一点吗?

标签: python

解决方案


一种可能的方法是利用glob模块来完成此任务和其他相关任务。

测试用例:

一个文件夹test包含 3 个子目录123. 每个子目录都包含 2 个pngtxt文件。

代码:

import os, glob

path = "test"
for root, dirs, files in os.walk(path, topdown=True):
   for name in dirs:
     print(glob.glob(root + '/' +  name + '/*.png'))

输出:

['test/1/2.png', 'test/1/1.png']
['test/3/4.png', 'test/3/5.png']
['test/2/4.png', 'test/2/3.png']

推荐阅读