37

how can i get the folder names existing in a directory using Python ?

I want to save all the subfolders into a list to work with the names after that but i dont know how to read the subfolder names ?

Thanks for you help

HightronicDesign
  • 603
  • 1
  • 8
  • 15

8 Answers8

49

You can use os.walk()

# !/usr/bin/python

import os

directory_list = list()
for root, dirs, files in os.walk("/path/to/your/dir", topdown=False):
    for name in dirs:
        directory_list.append(os.path.join(root, name))

print directory_list

EDIT

If you only want the first level and not actually "walk" through the subdirectories, it is even less code:

import os

root, dirs, files = os.walk("/path/to/your/dir").next()
print dirs

This is not really what os.walk is made for. If you really only want one level of subdirectories, you can also use os.listdir() like Yannik Ammann suggested:

root='/path/to/my/dir'
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print dirlist
  • 1
    thanks . But this code is just listing the names, however i cannot save them into an array or list ? – HightronicDesign Mar 23 '15 at 09:19
  • 1
    Sure you can... I've edited my answer, so it appends the entries to a list. – Christian Eichelmann Mar 23 '15 at 09:21
  • 1
    ahh really cool feature, there is still one problem, i am getting all the time the complete tree of all subdirectories in the path, i just need the first structure: C:\MyPath and in this folder i have folder1,folder2,folder3.... and i just need the folder1,folder2 etc names and not the subfolders of folder1..... – HightronicDesign Mar 23 '15 at 10:00
  • 1
    I've edited my answer again, regarding to your new condition. – Christian Eichelmann Mar 23 '15 at 10:19
  • 2
    Does this not work for python 3.x? I am getting `AttributeError: 'generator' object has no attribute 'next'` – ashley Oct 01 '19 at 20:24
  • 1
    `dir_lst = [os.path.join(root, name) for root, dirs, files in os.walk("/path/to/your/dir", topdown=False) for name in dirs ]` – Jithin Jun 25 '20 at 15:59
13

Starting with Python 3.4, you can also use the new pathlib module:

from pathlib import Path

p = Path('some/folder')
subdirectories = [x for x in p.iterdir() if x.is_dir()]

print(subdirectories)
poke
  • 339,995
  • 66
  • 523
  • 574
8

You can use os.listdir() here a link to the docs

Warning returns files and directories

example:

import os

path = 'pyth/to/dir/'
dir_list = os.listdir(path)

update: you need to check if the returned names are directories or files

import os

path = 'pyth/to/dir/'
# list of all content in a directory, filtered so only directories are returned
dir_list = [directory for directory in os.listdir(path) if os.path.isdir(path+directory)]
yamm
  • 1,413
  • 15
  • 24
7

You should import os first.

import os
files=[]
files = [f for f in sorted(os.listdir(FileDirectoryPath))]

This would give you list with all files in the FileDirectoryPath sorted.

titto.sebastian
  • 481
  • 2
  • 6
  • 17
5

I use os.listdir

Get all folder names of a directory

folder_names = []
for entry_name in os.listdir(MYDIR):
    entry_path = os.path.join(MYDIR, entry_name)
    if os.path.isdir(entry_path):
        folder_names.append(entry_name)

Get all folder paths of a directory

folder_paths = []
for entry_name in os.listdir(MYDIR):
    entry_path = os.path.join(MYDIR, entry_name)
    if os.path.isdir(entry_path):
        folder_paths.append(entry_path)

Get all file names of a directory

file_names = []
for file_name in os.listdir(MYDIR):
    file_path = os.path.join(MYDIR, file_name)
    if os.path.isfile(file_path):
        file_names.append(file_name)

Get all file paths of a directory

file_paths = []
for file_name in os.listdir(MYDIR):
    file_path = os.path.join(MYDIR, file_name)
    if os.path.isfile(file_path):
        file_paths.append(file_path)
oxidworks
  • 1,463
  • 1
  • 13
  • 34
3

Use os.walk(path)

import os

path = 'C:\\'

for root, directories, files in os.walk(path):
    for directory in directories:
        print os.path.join(root, directory)
mailtosumitrai
  • 691
  • 1
  • 7
  • 16
  • 1
    please how i am able to print only 2 down levels (sub directories) of directories... – Ossama Sep 11 '17 at 01:06
  • 1
    import os path = 'C:\\' for root, directories, files in os.walk(path): if root.replace(path, '').count(os.sep) <= 2: print root – mailtosumitrai Sep 12 '17 at 15:41
3

For python 3 I'm using this script

import os

root='./'
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
for dir in dirlist:
        print(dir)
Tech
  • 453
  • 1
  • 4
  • 13
1

Python 3.x: If you want only the directories in a given directory, try:

import os
search_path = '.'   # set your path here.
root, dirs, files = next(os.walk(search_path), ([],[],[]))
print(dirs)

The above example will print out a list of the directories in the current directory like this:

['dir1', 'dir2', 'dir3']

The output contains only the sub-directory names.
If the directory does not have sub-directories, it will print:

[]

os.walk() is a generator method, so use next() to only call it once. The 3-tuple of empty strings is for the error condition when the directory does not contain any sub-directories because the os.walk() generator returns 3-tuples for each layer in the directory tree. Without those, if the directory is empty, next() will raise a StopIteration exception.

For a more compact version:

dirs = next(os.walk(search_path), ([],[],[]))[1]
Traveler_3994
  • 87
  • 1
  • 8