2

I have one folder that contains many other folders. I want to able to extract those directory names and assign them to variables. I dont know the names of those folders and I dont know the quantity either. I need just the names of those folders and not the entire path.

Example:

inside \users\temp\ I have 2 directories. test1, test2

 folder[0] = test1

 folder[1] = test2

and so on....depending on how many directories I have.

Thank you

Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
user2353003
  • 492
  • 1
  • 6
  • 16

2 Answers2

2

You can use os.listdir and a list comprehension:

import os
path = r"\users\temp"   #use raw string as otherwise \t will be converted to tab space
folder = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path,x))]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
0
import os

print [name for name in os.listdir(".") if os.path.isdir(name)]

Or you can take reference from here List Directories and get the name of the Directory

os.path — Common pathname manipulations

Community
  • 1
  • 1
Ravi Pal
  • 385
  • 1
  • 7
  • 22