Python递归遍历多层嵌套文件夹并提取指定文件

凌晨两点半
凌晨两点半
发布时间:2026-10-13| 5人浏览过
原创

本文介绍如何利用Python递归函数处理多层嵌套文件夹中的文件读取问题。通过os.path.isfile判断文件类型,结合os.listdir遍历子目录,将符合条件的文件路径存入列表。文章对比了初始版本存在逻辑缺陷的代码与修正后的完整实现,重点解决混合目录下的读取报错问题,为批量处理日志等文件提供实用参考。

多层嵌套文件夹读取需求

因工作需求,需要深入读取多层嵌套结构文件夹内的文件,具体目录层级结构如下所示:

解决方案采用递归函数思路,利用Python内置的os.path.isfile方法检测当前路径是否为文件。若判定为目录而非文件,则调用os.listdir获取子目录列表,并对每个子项进行循环判断。

递归遍历实现方案

具体实现代码如下:


import os
path = 'abc'
path_read = []  #path_read saves all executable files

def check_if_dir(file_path):
  temp_list = os.listdir(file_path)  #put file name from file_path in temp_list
  for temp_list_each in temp_list:
    if os.path.isfile(file_path + '/' + temp_list_each):
      temp_path = file_path + '/' + temp_list_each
      if os.path.splitext(temp_path)[-1] == '.log':  #自己需要处理的是.log文件所以在此加一个判断
        path_read.append(temp_path)
      else:
        continue
    else:
      check_if_dir(file_path + '/' + temp_list_each)  #loop traversal

check_if_dir(path)
#print(path_read)

核心逻辑是将所有符合要求的文件路径通过字符串拼接方式,完整收集至一个列表中,以便在后续步骤中逐一提取并进行访问或操作。

在初期测试数据集中,观察到单个文件夹内要么仅包含子文件夹,要么仅包含文件。基于此假设,初次编写的函数直接通过temp_list[0]判断列表首项是否为文件。

然而,该初始版本存在显著缺陷:当文件夹内同时存在子文件夹和文件时,程序会尝试将文件夹路径当作文件读取,从而导致报错。

初始代码缺陷分析

初次编写的错误代码如下:


import os
path = 'abc'
path_read = []  #path_read saves all executable files

def check_if_dir(file_path):
  temp_list = os.listdir(file_path)  #put file name from file_path in temp_list

  if os.path.isfile(file_path + '/' + temp_list[0]):  #此处直接判断list中第一项是不是文件
    for temp_list_each in temp_list:
      temp_path = file_path + '/' + temp_list_each
      if os.path.splitext(temp_path)[-1] == '.log':
        path_read.append(temp_path)
      else:
        continue
  else:
    for temp_list_each in temp_list:
      check_if_dir(file_path + '/' + temp_list_each)  #loop traversal

check_if_dir(path)  #put all path in path_read
#print(path_read)

以上关于Python读取多层嵌套文件夹中文件的实例分享完毕,希望能为读者提供有益参考,欢迎继续支持本站获取更多技术内容。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。