1

How would you return a list of folders inside a directory? I just need their names. I know about glob.glob to list everything in a directory but I don't know how to filter it.

2 Answers2

3

You might combine list comprehension with some functions from os to print folders inside current catalog following way:

import os
folders = [i for i in os.listdir(os.getcwd()) if os.path.isdir(i)]
print(folders)

where:

  • os.getcwd gets current working directory
  • os.listdir returns list of everything inside given directory
  • os.path.isdir checks if i is directory

if you wish to do this for another catalog than current directory use os.chdir('path_to_your_catalog') after import os.

Daweo
  • 21,690
  • 3
  • 9
  • 19
2

You can do the following:

# Set root to whatever directory you want to check
root= os.getcwd()
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print (dirlist)
CDJB
  • 13,204
  • 5
  • 27
  • 47