how to get all folder only in a given path in python?

Question:

i’m using this code to get all files in a given folder. Is there a way to get only the folders ?

a = os.listdir('Tools')
Asked By: unice

||

Answers:

import os.path
dirs = [d for d in os.listdir('Tools') if os.path.isdir(os.path.join('Tools', d))]
Answered By: Ned Batchelder

To print only the folders

print os.walk(DIR_PATH).next()[1]

To print only the files

print os.walk(DIR_PATH).next()[2]
Answered By: Ark

Another method:

dirs = [entry.path for entry in os.scandir('Tools') if entry.is_dir()]
Answered By: Gerges
import os

def ld(val):
    return next(os.walk(val))[1] # Thank you @eryksun

for fold in ld('/'):
    print(fold)
Answered By: Itachi Sama

Use os.walk(DIR_PATH).next()[1]. Note os.walk(DIR_PATH).next() generates a tuple of length 3, where

  1. os.walk(DIR_PATH).next()[0] is the DIR_PATH
  2. os.walk(DIR_PATH).next()[1] is the list of all folders in the DIR_PATH
  3. os.walk(DIR_PATH).next()[2] is the list of all files in the DIR_PATH
Answered By: Meysam Sadeghi

Simple sample in python 3 for getting files and folders separated.

from os.path import isdir, isfile
from os import listdir

path = "./"

# get only folders
folders = list(filter(lambda x: isdir(f"{path}\{x}"), listdir(path)))

# get only files
files = list(filter(lambda x: isfile(f"{path}\{x}"), listdir(path)))
Answered By: niek tuytel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.