Python:最大递归深度

sur*_*esh 2 python recursion

下面给出了一个函数,用于返回其参数大小的总和,可以是单个文件/目录或文件/目录列表.代码给出了错误消息,RuntimeError: maximum recursion depth exceeded while calling a Python object但我尝试测试它.

如何解决这个问题?

谢谢

苏雷什

#!/usr/bin/python3.1
import os

def fileSizes(f):
    if hasattr(f,'__iter__'):
        return sum(filter(fileSizes,f))
    if os.path.isfile(f):
        return os.path.getsize(f)
    elif os.path.isdir(f):
        total_size = os.path.getsize(f)
        for item in os.listdir(f):
            total_size += fileSizes(os.path.join(f, item))
        return total_size
Run Code Online (Sandbox Code Playgroud)

Can*_*Can 8

而不是编写自己的adhoc目录 - 横向方法,而是使用内置os.walk (Documentation)方法.

实际上,文档中的示例(上面的链接)计算非目录文件的总大小.