Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead.
Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead.
Do you mean immediate subdirectories, or every directory right down the tree?
Either way, you could use os.walk
to do this:
os.walk(directory)
will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so
[x[0] for x in os.walk(directory)]
should give you all of the subdirectories, recursively.
Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it\'s not likely to save you much.
However, you could use it just to give you the immediate child directories:
next(os.walk(\'.\'))[1]
Or see the other solutions already posted, using os.listdir
and os.path.isdir
, including those at \"How to get all of the immediate subdirectories in Python\".
import os
d = \'.\'
[os.path.join(d, o) for o in os.listdir(d)
if os.path.isdir(os.path.join(d,o))]
You could just use glob.glob
from glob import glob
glob(\"/path/to/directory/*/\")
Don\'t forget the trailing /
after the *
.
If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.
If you only need the current directory\'s child directories, combine os.listdir
with os.path.isdir
Much nicer than the above, because you don\'t need several os.path.join() and you will get the full path directly (if you wish), you can do this in Python 3.5+
subfolders = [f.path for f in os.scandir(folder) if f.is_dir() ]
This will give the complete path to the subdirectory.
If you only want the name of the subdirectory use f.name
instead of f.path
https://docs.python.org/3/library/os.html#os.scandir
I prefer using filter (https://docs.python.org/2/library/functions.html#filter), but this is just a matter of taste.
d=\'.\'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
Implemented this using python-os-walk. (http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)
import os
print(\"root prints out directories only from what you specified\")
print(\"dirs prints out sub-directories from root\")
print(\"files prints out all files from root and directories\")
print(\"*\" * 20)
for root, dirs, files in os.walk(\"/var/log\"):
print(root)
print(dirs)
print(files)
You can get the list of subdirectories (and files) in Python 2.7 using os.listdir(path)
import os
os.listdir(path) # list of subdirectories and files
Since I stumbled upon this problem using Python 3.4 and Windows UNC paths, here\'s a variant for this environment:
from pathlib import WindowsPath
def SubDirPath (d):
return [f for f in d.iterdir() if f.is_dir()]
subdirs = SubDirPath(WindowsPath(r\'\\\\file01.acme.local\\home$\'))
print(subdirs)
Pathlib is new in Python 3.4 and makes working with paths under different OSes much easier: https://docs.python.org/3.4/library/pathlib.html
Thanks for the tips, guys. I ran into an issue with softlinks (infinite recursion) being returned as dirs. Softlinks? We don\'t want no stinkin\' soft links! So...
This rendered just the dirs, not softlinks:
>>> import os
>>> inf = os.walk(\'.\')
>>> [x[0] for x in inf]
[\'.\', \'./iamadir\']
Although this question is answered a long time ago. I want to recommend to use the pathlib
module since this is a robust way to work on Windows and Unix OS.
So to get all paths in a specific directory including subdirectories:
from pathlib import Path
paths = list(Path(\'myhomefolder\', \'folder\').glob(\'**/*.txt\'))
# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix
etc.
print(\"\\nWe are listing out only the directories in current directory -\")
directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir))
print(directories_in_curdir)
files = filter(os.path.isfile, os.listdir(os.curdir))
print(\"\\nThe following are the list of all files in the current directory -\")
print(files)
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(\'./\')
# List comprehension
[f for f in p.iterdir() if f.is_dir()]
# The trailing slash to glob indicated directories
# This will also include the current directory \'.\'
list(p.glob(\'**/\'))
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
Building upon Eli Bendersky\'s solution, use the following example:
import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
test_path = os.path.join(test_directory, child)
if os.path.isdir(test_path):
print test_path
# Do stuff to the directory \"test_path\"
where <your_directory>
is the path to the directory you want to traverse.
Here are a couple of simple functions based on @Blair Conrad\'s example -
import os
def get_subdirs(dir):
\"Get a list of immediate subdirectories\"
return next(os.walk(dir))[1]
def get_subfiles(dir):
\"Get a list of immediate subfiles\"
return next(os.walk(dir))[2]
With full path and accounting for path being .
, ..
, \\\\
, ..\\\\..\\\\subfolder
, etc:
import os, pprint
pprint.pprint([os.path.join(os.path.abspath(path), x[0]) \\
for x in os.walk(os.path.abspath(path))])
This answer didn\'t seem to exist already.
directories = [ x for x in os.listdir(\'.\') if os.path.isdir(x) ]
I\'ve had a similar question recently, and I found out that the best answer for python 3.6 (as user havlock added) is to use os.scandir
. Since it seems there is no solution using it, I\'ll add my own. First, a non-recursive solution that lists only the subdirectories directly under the root directory.
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:
for entry in rit:
if not entry.name.startswith(\'.\') and entry.is_dir():
dirlist.append(entry.path)
dirlist.sort() # Optional, in case you want sorted directory names
return dirlist
The recursive version would look like this:
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:
for entry in rit:
if not entry.name.startswith(\'.\') and entry.is_dir():
dirlist.append(entry.path)
dirlist += get_dirlist(entry.path)
dirlist.sort() # Optional, in case you want sorted directory names
return dirlist
keep in mind that entry.path
wields the absolute path to the subdirectory. In case you only need the folder name, you can use entry.name
instead. Refer to os.DirEntry for additional details about the entry
object.
use a filter function os.path.isdir
over os.listdir()
something like this filter(os.path.isdir,[os.path.join(os.path.abspath(\'PATH\'),p) for p in os.listdir(\'PATH/\')])
Copy paste friendly in ipython
:
import os
d=\'.\'
folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))
Output from print(folders)
:
[\'folderA\', \'folderB\']
If you want just the top list folder, please use listdir as walk take too much time.