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

目录内文件查找异常求助:Python代码无法遍历目录文件

问题分析与解决
  • 核心错误:代码使用了os模块的功能但未导入该模块,导致无法执行文件遍历逻辑。

修正后的完整代码:

import os

topdirectory = "./POSCARTEST/"
print(topdirectory)

def list_files_walk(start_path):
    fulllist = []
    for root, dirs, files in os.walk(start_path):
        for file in files:
            fulllist.append(os.path.join(root, file))
    
    return fulllist

directory_path = topdirectory
allfiles = list_files_walk(directory_path)
print(allfiles)

补充说明:

  1. 必须在代码开头添加import os,否则Python无法识别os.walk和os.path.join这些内置方法。
  2. 原代码中allfiles = list(list_files_walk(directory_path))的list()是多余的,因为函数已经返回列表类型,直接赋值即可。
  3. 若运行后仍为空列表,请检查./POSCARTEST/目录是否存在,以及目录内是否真的有文件(而非仅子目录)。

内容的提问来源于stack exchange,提问作者Mentor Toçani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:05:56