How to Get a List of All Subdirectories in the Current Directory in Python

Created
Modified

Using os.walk Function

The os.walk() method generates the file names in a directory tree by walking the tree either top-down or bottom-up.

The following example:

#!/usr/bin/python3

# Import module
import os

fs = os.walk(".")
for root, dirs, files in fs:
  print(files)
['demo.py', 'start.sh', 'file.txt']
['a.txt']

Using glob Function

using the glob function is the easiest way to get a list of all subdirectories in the current directory.

#!/usr/bin/python3

# Import module
import glob

fs = glob.glob("./*/*", recursive = True)
for f in fs:
  print(f)
./a/a.txt

Don't forget the trailing / after the *.

Related Tags