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

Python递归遍历所有文件失败:无法获取全部文件的问题排查

递归列出所有文件失败?看这里解决!

你的问题重现

你想递归遍历当前目录下的所有文件,目录结构是:

│ cat.py
│ cat2.py
│ du.py
│ README.md.txt
│ └───FirstInnerDirectory
│       file.txt
│       └───SecondInnerDirectory
               file2.txt

但你写的脚本没法获取到深层的file.txt和file2.txt,代码如下:

import os
def list_content_recursively(start_point):
    print("Call from: " + start_point)
    for entry in os.listdir(start_point):
        if os.path.isfile(entry):
            print("File: " + entry)
        elif os.path.isdir(entry):
            list_content_recursively(entry)
list_content_recursively(os.getcwd())

问题根源

核心问题是路径没处理对!os.listdir(start_point)返回的只是当前目录下的子项名称(比如FirstInnerDirectory),不是完整路径。当你调用os.path.isfile(entry)时,Python是在当前工作目录下找这个文件,而不是在start_point指定的目录里找。递归进入子目录后,路径更是混乱,自然找不到深层文件了。

修复方案

这里给你两种可行的修复方式,按需选择:

方案1:手动拼接完整路径(最直观)

用os.path.join()把当前目录和子项名称拼接成完整路径,这样所有判断和递归调用都基于正确的路径:

import os
def list_content_recursively(start_point):
    print("Call from: " + start_point)
    for entry in os.listdir(start_point):
        # 拼接出子项的完整路径
        full_entry_path = os.path.join(start_point, entry)
        if os.path.isfile(full_entry_path):
            print("File: " + full_entry_path)
        elif os.path.isdir(full_entry_path):
            list_content_recursively(full_entry_path)
list_content_recursively(os.getcwd())

方案2:用os.scandir()(更高效推荐)

Python 3.5+ 提供的os.scandir()会返回DirEntry对象,自带is_file()和is_dir()方法,而且直接包含完整路径,代码更简洁,性能也比os.listdir()更好(因为缓存了文件属性):

import os
def list_content_recursively(start_point):
    print("Call from: " + start_point)
    # 用with语句自动关闭scandir的迭代器
    with os.scandir(start_point) as entries:
        for entry in entries:
            if entry.is_file():
                print("File: " + entry.path)
            elif entry.is_dir():
                list_content_recursively(entry.path)
list_content_recursively(os.getcwd())

测试效果

运行修复后的代码,你就能看到所有文件了:

  • 根目录的cat.py、cat2.py等
  • FirstInnerDirectory下的file.txt
  • SecondInnerDirectory下的file2.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:24:35