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')
Answers:
import os.path
dirs = [d for d in os.listdir('Tools') if os.path.isdir(os.path.join('Tools', d))]
To print only the folders
print os.walk(DIR_PATH).next()[1]
To print only the files
print os.walk(DIR_PATH).next()[2]
Another method:
dirs = [entry.path for entry in os.scandir('Tools') if entry.is_dir()]
import os
def ld(val):
return next(os.walk(val))[1] # Thank you @eryksun
for fold in ld('/'):
print(fold)
Use os.walk(DIR_PATH).next()[1]
. Note os.walk(DIR_PATH).next()
generates a tuple of length 3, where
os.walk(DIR_PATH).next()[0]
is the DIR_PATH
os.walk(DIR_PATH).next()[1]
is the list of all folders in the DIR_PATH
os.walk(DIR_PATH).next()[2]
is the list of all files in the DIR_PATH
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)))
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')
import os.path
dirs = [d for d in os.listdir('Tools') if os.path.isdir(os.path.join('Tools', d))]
To print only the folders
print os.walk(DIR_PATH).next()[1]
To print only the files
print os.walk(DIR_PATH).next()[2]
Another method:
dirs = [entry.path for entry in os.scandir('Tools') if entry.is_dir()]
import os
def ld(val):
return next(os.walk(val))[1] # Thank you @eryksun
for fold in ld('/'):
print(fold)
Use os.walk(DIR_PATH).next()[1]
. Note os.walk(DIR_PATH).next()
generates a tuple of length 3, where
os.walk(DIR_PATH).next()[0]
is theDIR_PATH
os.walk(DIR_PATH).next()[1]
is the list of all folders in theDIR_PATH
os.walk(DIR_PATH).next()[2]
is the list of all files in theDIR_PATH
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)))