d3pd
d3pd

Reputation: 8315

how to make a recursive function that builds a list

What would be a good way to get a recursive function to build a list for return? Let's say I have a function like the following for generating a listing of files and directories at all subdirectories:

def print_directory_listing(directory = "."):                          
    for file_structure in os.listdir(directory):                
        file_structure_path = os.path.join(directory, file_structure)
        if os.path.isdir(file_structure_path):
            print_directory_listing(file_structure_path)
        else:
            print(file_structure_path)

Rather than printing out everything, how could I modify this to return a list of all of the files and directories? For example, would it be good to have a global list to which the function appends files?

Note that I am not asking for details on os.walk; I am asking a general question on what the Pythonic way would be to get a recursive function to build and return a list.

Upvotes: 0

Views: 918

Answers (1)

user3672754
user3672754

Reputation:

Thanks to your comment I think having understood the real purpose of your question. If you take a look to the following code, you will find the recursion you are looking for and you will see how to "save the variables of the childs".

import os

def print_directory_listing(directory = '.'):
    files_list=[]

    for file_structure in os.listdir(directory):                
        file_structure_path = os.path.join(directory, file_structure)
        if os.path.isdir(file_structure_path):
            files_list+=print_directory_listing(file_structure_path)
        else:
            files_list.append(file_structure_path)

    return files_list

Upvotes: 1

Related Questions