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

如何遍历指定文件夹及其所有层级子目录的PNG文件,生成含路径与文件名的tuple数组

遍历指定目录生成PNG文件元组数组实现方案

以下是Python语言的两种可直接运行的实现:


方案1:os模块实现(兼容所有Python版本)

核心用os.walk递归遍历所有层级目录,自动筛选PNG格式文件:

import os

def collect_png_files(root_folder):
    png_tuple_array = []
    # 递归遍历所有子目录
    for dir_path, _, file_names in os.walk(root_folder):
        for file_name in file_names:
            # 匹配.png后缀(包含大写.PNG的情况)
            if file_name.lower().endswith('.png'):
                png_tuple_array.append( (dir_path, file_name) )
    return png_tuple_array

调用示例:

# 替换为你要遍历的文件夹路径
target_folder = "/path/to/your/target/folder"
result_array = collect_png_files(target_folder)

注意:Windows系统下传入路径建议使用raw字符串格式(如r"C:\Users\xxx\Pictures"),避免转义字符报错。

返回的result_array就是你需要的、存储了所有(目录路径, 文件名)元组的数组。


方案2:pathlib实现(Python3.4+ 写法更简洁)

用pathlib的递归全局匹配逻辑,代码更短可读性更高:

from pathlib import Path

def collect_png_files(root_folder):
    root = Path(root_folder)
    # rglob递归匹配所有png文件,包含大写后缀
    return [ (str(png_file.parent), png_file.name) for png_file in root.rglob("*.[pP][nN][gG]") ]

调用方式和方案1完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:42:02