python - python 递归目录树

标签 python recursion os.walk

def mapping(list_of_files , list_of_folders, max1):
    print max1
    max1 += 1

    if len(list_of_folders) == 0:
        folder = os.walk(os.getcwd()).next()[1]
        files = os.listdir(os.getcwd())
    elif len(list_of_files) != 0:
        print list_of_folders[0]
        ## for some reason this of line of code stops working without error on 20150 iteration 
        folder = next(os.walk(os.getcwd() +'/' + list_of_folders[0]))[1]
        #folder = os.walk(os.getcwd() +'/' + list_of_folders[0] ).next()[1]
        #print os.listdir(os.getcwd() + '/' +list_of_folders[0])
        files = os.listdir(os.getcwd() + '/' +list_of_folders[0])


    length = len(folder)
    length1 = len (files)

    y = 0
    if folder == files:
        del files[:] 
    else :
        for x in range(length):
            while y != length1:
                if files[y] == folder[x]:
                    files.pop(y)
                    length1 = length1 - 1
                    y = 0
                y += 1
            y = 0

    #print folder
    #print files

    if len(list_of_folders) == 0:
        list_of_files = add_to_main_lists(list_of_files,'', files)
        #print list_of_files
        list_of_folders = add_to_main_lists(list_of_folders, '', folder)
        #print list_of_folders
    else:
        list_of_files = add_to_main_lists(list_of_files,list_of_folders[0], files)
        #print list_of_files
        list_of_folders = add_to_main_lists(list_of_folders, list_of_folders[0], folder)
        #print list_of_folders
        list_of_folders.pop(0)


    if len(list_of_folders) == 0:
        print "got to here"
        return  list_of_files 
    else:
        print "file length: " + str(len(list_of_files))
        print "folder length: " + str(len(list_of_folders))
        mapping(list_of_files , list_of_folders, max1)

    return list_of_files

list_of_files = []
list_of_folders = []
list_of_files = mapping(list_of_files, list_of_folders , max1)
print (list_of_files)

该文件应该映射出文件所在的文件夹及其所有子目录。由于某种原因,当代码运行其 20150 迭代时,该行 文件夹 = next(os.walk(os.getcwd() +'/' + list_of_folders[0]))[1] 终止代码并且不会抛出任何错误。我不知所措。我使用 sudo 运行代码。

最佳答案

我可以在代码中看到两件事:

  • 您在同一迭代中对生成器调用 .next() 两次。我认为这不是您想要做的,您的迭代将解析两个不同的 os.walk 输出。将 os.walk(os.getcwd()).next() 的输出保存在 var 中并使用它。

  • 仅当当前级别中没有文件夹时,您才会处理文件列表,因为您正在使用 elif 执行 list_of_files。您应该使用 if,因为无论如何您都想处理它。

此外,请记住迭代器的末尾会引发 StopIteration 异常,因此这很可能会发生。您需要处理该异常。

关于python - python 递归目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105525/

相关文章:

python - 如何使用 Python 实现用户身份验证和 session

Java递归函数判断两个连续数字是否相等

Python:猴子修补函数的源代码

python - 在 MAC OS X 上,py.test 不被识别为命令

c++ - 递归调用溢出

algorithm - 另一个内部递归调用的递归关系

python - 如何更改列表中文件的文件扩展名

python - 使用 os.walk() 循环文件并打开它们

python - 寻求目录树数据表示的优雅设计

python - 使用 PIL/Pillow 打开 PNG