-1

I am trying to iterate through a folder, where inside it, I will be having multiple other folders, each could contain other subfolders. An example of the tree could be:

Dataset_Directory
  | Folder A
  | Folder B
  | Folder C
  | Folder D
      | Folder D1
      | Folder D1
  

What I am trying to do is to only get the man 4 foulders, which are A,B,C,D and ignore any sub-folders.

My code:

    folders = [os.path.basename(os.path.normpath(x[0])) for x in os.walk(
        app.config['DATASET_DIRECTORY']) if x[0] != 'static\Dataset_Directory']

    for folder in folders:
        print(folder)

This outputs all folders and sub-folders inside the list as os.walk gets all from the directory tree. The output is as follows:

Folder A
Folder B
Folder C
Folder D
Folder D1
Folder D2

What I'm trying to achieve is only

Folder A
Folder B
Folder C
Folder D

Any suggestion on how to stop it from reading through sub-folders? Thanks in advance.

2 Answers2

1

You can try this:

import os.path
dirs = [d for d in os.listdir('Dataset_Directory') if os.path.isdir(os.path.join('Dataset_Directory', d))]
print(dirs)

Output:

['Folder A', 'Folder C', 'Folder D', 'Folder B']
Sabil
  • 3,750
  • 1
  • 5
  • 16
1

You can also utilize the pathlib library as follows:

from pathlib import Path
print([x.name for x in Path('Dataset_Directory').iterdir() if x.is_dir()])  

Yields:

['Folder A', 'Folder C', 'Folder D', 'Folder B']
itprorh66
  • 3,110
  • 4
  • 9
  • 21