-1

In this a variable there is a folder called main_folder. This folder has two folders:

111,222

I need to get the names of these folders in a list.

Tried this:

a = r'C:\Users\user\Desktop\main_folder'
import os 
for root, dirs, files in os.walk(a):
    print(dirs)

gives:

['111', '222'] # <--------------This only needed
[]
[]

How to keep only the first list and not the empty ones which I think describe the contents of these folders since they don't have folders.

2 Answers2

0

This function will do the job:

import os
def get_immediate_subdirectories(a_dir): ##a_dir is the path of the main folder
    return [name for name in os.listdir(a_dir) ## returns all the immediate subfolders
            if os.path.isdir(os.path.join(a_dir, name))] ## keeps checking the name + file is here

Calling Function:

get_immediate_subdirectories("Path")
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
0

Iterate just once via next:

import os

a = r'C:\Users\user\Desktop\main_folder'
walker = os.walk(a)
res = next((dirs for _, dirs, _ in walker), [])

If necessary, you can continue iterating walker via additional next calls.

jpp
  • 159,742
  • 34
  • 281
  • 339