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

如何获取目录下所有文件的扩展名并返回list/tuple格式结果

Python 实现指定目录全文件扩展名枚举

核心思路

不需要提前构建扩展名匹配库,仅通过一次目录遍历即可完成采集,时间复杂度为O(n),文件量越大效率优势越明显,天然兼容所有标准、自定义扩展名格式。

  • 遍历目标目录下的所有文件条目,跳过子目录、符号链接(可按需配置是否跟随)
  • 用标准库自带的文件名拆分方法提取后缀,自动适配.source_1这类自定义扩展名、多段扩展名场景
  • 用集合做存储自动去重,最终按需求转换为列表/元组返回

基础实现(仅遍历当前目录,不递归子文件夹)

依赖Python标准库os,无需安装第三方包:

import os

def collect_dir_extensions(target_path: str, return_tuple: bool = False) -> list | tuple:
    ext_collection = set()
    # scandir 是Python3.5+提供的高性能目录遍历接口,大目录下遍历效率远高于listdir
    with os.scandir(target_path) as entries:
        for entry in entries:
            # 仅处理文件,跳过文件夹、不跟随软链避免循环引用死循环
            if entry.is_file(follow_symlinks=False):
                # splitext 原生支持任意格式扩展名拆分,无需自定义正则匹配
                _, suffix = os.path.splitext(entry.name)
                # 去掉后缀开头的点,统一转小写做归一化
                clean_suffix = suffix.lstrip(".").lower()
                if clean_suffix:
                    ext_collection.add(clean_suffix)
    return tuple(ext_collection) if return_tuple else list(ext_collection)

调用示例

# 获取./test目录下的所有扩展名,返回列表格式
ext_list = collect_dir_extensions("./test")
print(ext_list)
# 输出样例: ['txt', 'png', 'xml', 'pdf', 'source_1']

# 需要元组格式时传入对应参数即可
ext_tuple = collect_dir_extensions("./test", return_tuple=True)

扩展实现(递归遍历所有子目录)

如果需要采集目标目录下所有层级子文件夹内的文件扩展名,替换遍历逻辑为os.walk即可:

import os

def collect_dir_extensions_recursive(target_path: str, return_tuple: bool = False) -> list | tuple:
    ext_collection = set()
    for root, _, file_names in os.walk(target_path, followlinks=False):
        for name in file_names:
            _, suffix = os.path.splitext(name)
            clean_suffix = suffix.lstrip(".").lower()
            if clean_suffix:
                ext_collection.add(clean_suffix)
    return tuple(ext_collection) if return_tuple else list(ext_collection)

适配说明

  • 如果需要区分大小写扩展名(比如.TXT和.txt判定为不同后缀),删除代码中.lower()的调用即可
  • 如果需要保留扩展名前的.,删除.lstrip(".")的调用即可
  • 如果需要统计无扩展名的文件,直接在集合中添加空字符串标记即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:45:38