0

i'm trying to write a python sw that takes every file in a defined directory and searches them in an another directory by means of the subdirectories' names in which files are contained. To do so i'm using os functions to navigate through files in my directory and nested functions to search for the directories in the destination path

def searchdirs(destination_dir,name):

    for file in os.listdir(destination_dir):
        d = os.path.join(destination_dir, file)
        if os.path.isdir(d):
            if file=="Custom":
                continue

            if file==name:
                print(d) #if i find a folder with the name i'm looking for i want to return the path               
                return d           
            else:
                searchdirs(d,name) #if the dir hasn't the name i want i start over
                


def search_file(file_infos,n_dirs,dest_directory,device):

    
    if n_dirs>=1:
        app_dir=dest_directory 
        print(n_dirs)
        while n_dirs>0 : # i repeat the loop until i have no more sub dirs
            folder_name=file_infos[n_dirs]  //take the first folder name and i start the search
            app_dir=searchdirs(app_dir,folder_name)
            print(app_dir)
            n_dirs-=1 

        return app_dir    



for root, dirs, files in os.walk(source_dir):
    for file in files:     
        source_path = os.path.join(root, file)
        p=Path(source_path)
        p=p.parts[::-1] #invert the list
        idx_dirs=p.index(custom_dir) # here i check if source files arein the main source directory 
                                       or in various sub directories
        sub_dirs=idx_dirs-1  #here i'm counting how many subdirs are present for that file
        t=search_file(p,sub_dirs,destination_dir,device)

the issue is that the nested functions overwrite my buffer and thus i'm not able to retrieve the path of the folder i found

  • That **isn't "nested"**; it's *recursive*. This is an extremely common problem; please see the linked duplicate. The short version for your case is that you need to explicitly check whether the recursive call returned a match, and explicitly `return` that result if so. (If it returns `None`, then the code should just do nothing, in order to resume the `for` loop and keep searching.) – Karl Knechtel Mar 01 '23 at 17:42
  • Thank you very much for your suggestion! I figured out that i could catch the return of recursive function directly after its inner call. – Marmorn Mar 01 '23 at 22:31

0 Answers0