python - 遍历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中如何做到这一点吗?
解决方案
一种可能的方法是利用glob
模块来完成此任务和其他相关任务。
测试用例:
一个文件夹test
包含 3 个子目录1
,2
和3
. 每个子目录都包含 2 个png
和txt
文件。
代码:
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']
推荐阅读
- azure-devops - 添加“未使用”的 VSTS 任务组参数
- html - 创建具有相同大小图像的响应式弹性框
- assembly - 引导加载程序不断将 eax 添加到 al
- struts2 - Struts2 Action 未调用,但请求到达服务器
- jekyll - jekyll + 液体中的 if 语句创建代码块而不是意图的 html 标签
- java - 将遗留应用程序配置从 HTTPS 更改为 HTTP 后 Spring Security 停止工作
- vue.js - 使用 SVG 文件使用 Vuetify 创建视差效果
- python - 从 Docker 容器内部对潜在的极端 URL 运行 GET 请求是否安全?
- wordpress - 我想显示我的功能,但它不显示
- typo3 - 创建 TYPO3 VHS 引导导航栏