0

I would like to know if there's a quick 1 line of code to list all the directories in a directory. It's similar to this question: How do I list all files of a directory? , but with folders instead of files.

Brad123
  • 877
  • 10
  • 10

4 Answers4

3

Here is a recipe for just the first level:

dname = '/tmp'
[os.path.join(dname, d) for d in next(os.walk(dname))[1]]

and a recursive one:

dname = '/tmp'
[os.path.join(root, d) for root, dirs, _ in os.walk(dname) for d in dirs]

(after import os, obviously)


Note that on filesystems that support symbolic links, any links to directories will not be included here, only actual directories.

alani
  • 12,573
  • 2
  • 13
  • 23
1

Using os.listdir to list all the files and folders and os.path.isdir as the condition:

import os   
cpath = r'C:\Program Files (x86)'
onlyfolders = [f for f in os.listdir(cpath) if os.path.isdir(os.path.join(cpath, f))]
Brad123
  • 877
  • 10
  • 10
  • 1
    Probably worth noting here that this _includes_ any symbolic links to directories. This behaviour contrasts with the version based on `os.walk` which I posted, which _excludes_ them. The question is not explicit about which behaviour is required, but users should be aware of the difference. – alani Jun 22 '20 at 22:35
  • Thanks for the comment. I was not aware of this. – Brad123 Jun 24 '20 at 00:07
0

Import os

#use os.walk()

Example:

For folder, sub, file in os.walk(path): Print(folder). #returns parent folder Print (sub). #returns sub_folder Print (file) # returns files

Chairman
  • 134
  • 1
  • 10
0
[ i[0] for i in os.walk('/tmp')]
  1. here '/tmp' is the directory path for which all directories are listed
  2. you need to import os

This works because i[0] gives all the root paths as it will walk through them so we don't need to do join or anything.

Sandeep Kothari
  • 405
  • 3
  • 6