You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用os.listdir()仅返回上层文件夹名,无法获取子目录内PNG文件名如何处理

问题原因

你使用的os.listdir()仅会返回目标路径下的直接子元素(包含文件夹、文件),不会递归进入子目录扫描内部文件,因此只能拿到SPRING4799、SPRING4800这类一级子文件夹名,无法获取嵌套在子文件夹内的png文件名。


解决方案

方案1:使用os.walk实现递归扫描(兼容所有Python版本)

import os

root_path = '/content/images/maleset/'
png_file_names = []

# 递归遍历root_path下所有子目录
for current_dir, _, file_list in os.walk(root_path):
    for file in file_list:
        # 可根据需求添加命名规则过滤,比如if file.startswith('SPRING') and file.endswith('.png'):
        if file.endswith('.png'):
            # 仅保存文件名,如需完整路径改为png_file_names.append(os.path.join(current_dir, file))
            png_file_names.append(file)

# 输出所有目标文件名
print(png_file_names)

方案2:使用pathlib实现(Python 3.4+ 推荐,语法更简洁)

from pathlib import Path

root_path = Path('/content/images/maleset/')
# 递归匹配所有png文件,rglob参数可自定义匹配规则,比如'SPRING*-D*-V*.png'
png_file_names = [file.name for file in root_path.rglob('*.png')]

print(png_file_names)

内容的提问来源于stack exchange,提问作者lingyau lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:36:03