【问题标题】:How to make this files function non-recursive?如何使这些文件具有非递归功能?
【发布时间】:2019-12-13 22:52:36
【问题描述】:

这是一个列出当前文件夹和子文件夹中所有文件的函数,它是递归的,我不能非递归地写它

我尝试使用嵌套格式的 while 和 for 循环,但无法使其工作。

def recur_files(start_dir):
    files = []
    original_path = os.getcwd()
    os.chdir(start_dir)
    items = os.listdir()
    for item in items:
        if "." in item:
            files.append(os.path.abspath(item))
        else:
            files.extend(recur_files(os.path.abspath(item)))
    os.chdir(original_path)
    return files

【问题讨论】:

  • 使用os.walk() 获取文件夹和子文件夹中的所有文件。
  • 要使其不使用递归(并且不使用 os.walk),您必须对目录使用列表并使用从该列表中获取 dirname 的循环。如果找到子文件夹,则将 dirname 添加到此列表中,下次循环应从列表中获取它。

标签: python file recursion directory operating-system


【解决方案1】:

您可以使用os.walk() 获取文件夹和子文件夹中的所有文件。

但是如果你想创建自己的函数,那么你需要目录列表。循环应该从此列表中获取目录名,您应该将新目录添加到此列表中,而不是使用新的 start_dir 运行函数

import os

def recur_files(start_dir):
    files = []
    dirs = [start_dir]

    for dirname in dirs:
        for item in os.listdir(dirname):

            fullpath = os.path.join(dirname, item)

            if os.path.isdir(fullpath): #and fullpath not in ('.', '..'):
                dirs.append(fullpath)
            else:
                files.append(fullpath)

    return files, dirs

recur_files('.')

【讨论】:

  • 非常感谢。非常有帮助。我将使用 os.walk()。我还学会了将递归函数转换为非递归函数。
【解决方案2】:

如果你想以深度优先搜索的方式列出你的文件而不使用程序堆栈(也就是通过递归),你总是可以创建自己的堆栈(只是 Python 中的一个列表)并编写一个简单的 DFS 算法,如下所示。

import os


def recur_files():
    original_path = os.getcwd()
    stack = os.listdir()
    results = []

    for item in stack:
        os.path.join(original_path, item)

    while stack:
        elem = stack.pop(0)
        if os.path.isdir(elem):
            results.append(elem)
            for item in os.listdir(elem):
                stack = [os.path.join(elem, item)] + stack
        else:
            results.append(elem)

    return results

【讨论】:

  • 非常感谢您!这教会了我如何处理任何递归函数。
【解决方案3】:

示例:

from os import walk

files = []
for _, _, filenames in walk(your_path):
    files.extend(filenames)
print("Files: {}".format(files))

您可以递归地获取路径中的所有文件。

【讨论】:

  • 非常感谢您。它满足了我的目的。非常棒。
猜你喜欢
  • 2017-02-20
  • 1970-01-01
  • 2020-02-04
  • 2014-01-03
  • 2013-11-10
  • 2017-02-20
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多