【问题标题】:Recursive function does not recurse递归函数不递归
【发布时间】:2015-03-01 04:18:53
【问题描述】:

我在 Python 3 中定义了一个函数...

>>> import os
>>> def find(path):
...   if not os.path.isdir(path):
...     return []
...   out_list = []
...   for f in os.listdir(path):
...     if os.path.isdir(f):
...       for g in find(f):
...         out_list.append(g)
...     else:
...       out_list.append(f)
...   return out_list
... 

这似乎会爬下path 的树并列出每个文件(无论如何对我来说),但是当我执行它时......

>>> find('..')
['CDB', 'dv', 'DataIntegrityUtility', 'cdb', 'libvrs']

所有结果都有包含文件的目录。不应该还有更多吗?

【问题讨论】:

  • 为什么不将find 设为生成器,将yield 设为您找到的文件?代码在内存方面会更简单,更有效。而当你必须有一个清单的时候,你可以打电话给list()

标签: python file python-3.x recursion directory


【解决方案1】:

问题是,

for f in os.listdir(path):

将使用路径中包含的“叶子”名称进行迭代,例如,如果 path 是 '/tmp/fooand it containsbarandbazandbaz, thenfwill bebar, thenbaz`。

但是然后你检查os.path.isdir('bar')——这意味着'bar'如果在当前目录中有的话,不是'/tmp'下的那个!

所以你需要添加类似的东西

f = os.path.join(path, f)

就在for 语句的下方,以便其余逻辑正确运行。 (如果您出于某种原因只想要 out_list 中的叶子名称,您可以使用 os.path.basename 从完整路径字符串中提取它们。

【讨论】:

    【解决方案2】:

    在python中存在os.walk

    os.walk('path') => 递归遍历目录,给出带有目录的元组,

    子目录和文件

    for x,y,z in os.walk('path'):
        # z is the directory
        # y is subdirectories
        # x is the files
    

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2010-12-25
      • 2023-04-02
      • 2016-01-06
      相关资源
      最近更新 更多