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

Python递归目录遍历函数为何未返回全部文件数据?

问题原因及修复方案

核心问题

你这个函数的问题出在递归调用时没有接收返回的数组。因为np.append()不会修改原数组,而是返回一个新的数组对象。当你递归进入子目录调用read_path时,子函数里生成的包含子目录文件的新数组没有被赋值回当前的items变量,所以上层的items根本没拿到子目录的文件路径,最后只返回了根目录的文件。

另外还有两个小问题:

  • 用"." in item判断文件不严谨,文件夹名字里也可能带点(比如.vscode),应该用os.path.isfile()来准确判断是否为文件。
  • 手动拼接路径f"{path}\{item}"跨平台兼容性差,建议用os.path.join()来拼接路径。

修正后的代码

import os
import numpy as np

def read_path(path, items):
    for item in os.listdir(path):
        full_path = os.path.join(path, item)
        if os.path.isfile(full_path):
            items = np.append(items, full_path)
            print(f"File: {item}")
        else:
            # 接收递归返回的数组,更新当前items
            items = read_path(full_path, items)
            print(f"Folder: {item}")
    return items

f = np.array([])
result = read_path(r"D:\Reubens stuff\Code Stuff\code saves\Python\Create Texture Pack\samples-load\resource_pack\textures", f)
print(result)

额外优化建议

如果文件数量较多,np.append()会频繁创建新数组,效率很低。可以先改用Python列表收集路径,最后再转成numpy数组,性能会好很多:

import os
import numpy as np

def read_path(path):
    items = []
    for item in os.listdir(path):
        full_path = os.path.join(path, item)
        if os.path.isfile(full_path):
            items.append(full_path)
            print(f"File: {item}")
        else:
            items.extend(read_path(full_path))
            print(f"Folder: {item}")
    return items

# 最后转成numpy数组
result = np.array(read_path(r"D:\Reubens stuff\Code Stuff\code saves\Python\Create Texture Pack\samples-load\resource_pack\textures"))
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:56:11