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

如何在Python中遍历子目录并按目录分组获取所有文件

按目录分组递归处理文件并调用函数

需求说明

需要递归遍历目录中的每个文件夹,将文件夹内的所有文件(包括子文件夹里的文件)按所属目录分组,把该目录下的所有文件连同文件夹名称一起传入指定函数myfunc。

示例文件结构

├── root_folder
│   ├── subdir1
│   │   ├── file1.txt
│   │   ├── file2.txt
│   ├── subdir2
│   │   ├── file3.txt
│   ├── subdir3
│   │   ├── file4.txt
│   │   ├── file5.txt
│   │   ├── file6.txt
│   ├── subdir4
│   |   ├── subdir42
│   │   |   ├── file7.txt
│   │   ├── subdir43
│   │   |   ├── file8.txt
│   │   |   ├── file9.txt

期望的函数调用效果

  • myfunc("file1.txt", "file2.txt", "subdir1")
  • myfunc("file3.txt", "subdir2")
  • myfunc("file4.txt", "file5.txt", "file6.txt", "subdir3")
  • myfunc("file7.txt", "subdir42")
  • myfunc("file8.txt", "file9.txt", "subdir43")

现有问题

当前代码只能逐个输出文件路径,无法按目录分组处理:

indir = "C:/path/to/indir"
for path, directories, files in os.walk(indir):
     for file in files:
        fpath = os.path.join(path, file)
        print(fpath)

解决方案

修改代码,利用os.walk的特性直接按目录分组处理:

import os

def myfunc(*args):
    # 这里替换成你的实际函数逻辑
    print("调用myfunc:", args)

indir = "C:/path/to/indir"
for path, directories, files in os.walk(indir):
    if not files:
        continue  # 跳过没有文件的目录
    # 提取当前文件夹的名称(而非完整路径)
    folder_name = os.path.basename(path)
    # 组装参数:先传所有文件名,最后传文件夹名称
    func_args = files + [folder_name]
    # 调用函数
    myfunc(*func_args)

代码说明

  1. os.walk(indir)会递归遍历目标目录下的所有子目录,每次迭代返回当前目录路径、子目录列表、当前目录下的文件列表。
  2. 跳过空目录(没有文件的目录),避免无效调用。
  3. 用os.path.basename(path)获取当前文件夹的名称(比如从C:/path/to/root_folder/subdir1提取subdir1)。
  4. 将文件列表和文件夹名称组合成参数列表,通过*func_args解包后传入myfunc,实现需求中的调用格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:30:08