Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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') 
like image 710
unice Avatar asked Oct 16 '11 00:10

unice


People also ask

How do you get the paths of all files in a folder in Python?

os. listdir() returns everything inside a directory -- including both files and directories. A bit simpler: (_, _, filenames) = walk(mypath). next() (if you are confident that the walk will return at least one value, which it should.)

How do you get all files in the directory using a in Python?

os. listdir() method gets the list of all files and directories in a specified directory.

How do I create a folder within a specific path in Python?

Using os. os. mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists.


Video Answer


2 Answers

import os.path dirs = [d for d in os.listdir('Tools') if os.path.isdir(os.path.join('Tools', d))] 
like image 77
Ned Batchelder Avatar answered Sep 21 '22 01:09

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] 
like image 25
Ark Avatar answered Sep 19 '22 01:09

Ark