1

i need some tips and help with my problem. I want so make a dropdown menu in jupyter notebooks over a directory. Inside this directory are dir´s with png´s, and some dir´s with subdir´s with png´s. Now i wanna get a list of all dir´s with png´s inside. But not the dir´s with dir´s inside. ATM i get every dir, but thats wrong cause i just can use dir´s with png´s inside. Thats my code atm:

dir_path = 'Learning set/Calanus hyp/Chyp 1/'
path = 'Learning set/'   

for root, dirs, files in os.walk(path):
    for name in dirs:
        if ([os.path.isfile(os.path.join(path, f)) for f in os.listdir(path)]) == True:
            namelist += [os.path.join(root,name)]

def get_and_plot(b):
    clear_output()
    global dir_path
    dir_path_new=test.value+"/"
    dir_path=dir_path_new
    global counter
    counter=0
    execute()

test.observe(get_and_plot, names='value')

As an example: I have the directory "Learing Set" and wanna get a dropdown. But the dropdown menu shows me the dir´s Bubble, Bubble1, Bubble2 etc. The dir´s BubbleX have pngs inside. Thats correct. But the Bubble dir just implements the other BubbleX dir´s. What can i do, to get a list of all last subdir´s?

jnp
  • 21
  • 3
  • Question is very similar to [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/q/3964681/2823755) - the difference being you want to *capture* the directories instead of the files themselves. So not quite a duplicate. – wwii Mar 29 '19 at 15:31

1 Answers1

1

root will be the current directory during the walk. If any of its files meet your criteria, add root to a list (or some other container).

dirs_i_want = []
for root, dirs, files in os.walk(path):
    if any(fyle.endswith('png') for fyle in files:
        dirs_i_want.append(root)

If you want directories that only contain files that meet your criteria, use all in the conditional statement.

...
    if all(fyle.endswith('png') for fyle in files:
        ...
wwii
  • 23,232
  • 7
  • 37
  • 77