I want to be able to list only the directories inside some folder. This means I don\'t want filenames listed, nor do I want additional sub-folders.
Let\'s see if an
-- This will exclude files and traverse through 1 level of sub folders in the root
def list_files(dir):
List = []
filterstr = ' '
for root, dirs, files in os.walk(dir, topdown = True):
#r.append(root)
if (root == dir):
pass
elif filterstr in root:
#filterstr = ' '
pass
else:
filterstr = root
#print(root)
for name in files:
print(root)
print(dirs)
List.append(os.path.join(root,name))
#print(os.path.join(root,name),"\n")
print(List,"\n")
return List
A very much simpler and elegant way is to use this:
import os
dir_list = os.walk('.').next()[1]
print dir_list
Run this script in the same folder for which you want folder names.It will give you exactly the immediate folders name only(that too without the full path of the folders).
Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths:
from pathlib import Path
p = Path('./')
[f for f in p.iterdir() if f.is_dir()]
A safer option that does not fail when there is no directory.
def listdirs(folder):
if os.path.exists(folder):
return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
else:
return []
Filter the list using os.path.isdir to detect directories.
filter(os.path.isdir, os.listdir(os.getcwd()))
Note that, instead of doing os.listdir(os.getcwd())
, it's preferable to do os.listdir(os.path.curdir)
. One less function call, and it's as portable.
So, to complete the answer, to get a list of directories in a folder:
def listdirs(folder):
return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
If you prefer full pathnames, then use this function:
def listdirs(folder):
return [
d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
if os.path.isdir(d)
]