Search code examples
pythonrecursion

Why is my recursive function not returning all of the data?


I have a python function to return all the files in some directory (and its sub-directories) as a numpy array, it goes over all of the files (as shown by the print statement), but only returns the ones in the file path specified, whats happening? Heres my minimal reproducible version:

import os
import numpy as np

def read_path(path, items):
    for item in os.listdir(path):
        if "." in item:
            items = np.append(items, f"{path}\{item}")
            print(f"File: {item}")
        else:
            read_path(f"{path}\{item}", items)
            print(f"Folder: {item}")
    return items

f = np.array([])
print(
    read_path(r"D:\Reubens stuff\Code Stuff\code saves\Python\Create Texture Pack\samples-load\resource_pack\textures", f)
)

Solution

  • As pointed out by David, you need to add the return value of the recursion to the original items array. Hence, the following code should work:

    import os
    import numpy as np
    
    def read_path(path, items):
        for item in os.listdir(path):
            full_path = os.path.join(directory_path, item)
            if os.path.isfile(full_path):
                items = np.append(items, f"{path}\{item}")
                print(f"File: {item}")
            else:
                items = np.append(items, read_path(f"{path}\{item}", items))
                print(f"Folder: {item}")
        return items
    
    f = np.array([])
    print(
        read_path(r"D:\Reubens stuff\Code Stuff\code saves\Python\Create Texture Pack\samples-load\resource_pack\textures", f)
    )