Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of subdirectories names [duplicate]

Tags:

python

list

There is a directory that contains folders as well as files of different formats.

import os 
my_list = os.listdir('My_directory')

will return full content of files and folders names. I can use, for example, endswith('.txt') method to select just text files names, but how to get list of just folders names?

like image 858
Andersson Avatar asked Jun 25 '15 11:06

Andersson


People also ask

How do I get a list of file names from a folder and subfolders?

Hover the cursor on the 'From File' option and click on 'From Folder'. In the Folder dialog box, enter the folder path, or use the browse button to locate it. Click OK. In the dialog box that opens, you'll see the names of all the files along with other metadata.

How do I list all subdirectories in Windows?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.


5 Answers

os.walk already splits files and folders up into different lists, and works recursively:

for root,dirs,_ in os.walk('.'):
    for d in dirs:
        print os.path.join(root,d)
like image 123
user1016274 Avatar answered Oct 03 '22 10:10

user1016274


I usually check for directories, while assembling a list in one go. Assuming that there is a directory called foo, that I would like to check for sub-directories:

import os
output = [dI for dI in os.listdir('foo') if os.path.isdir(os.path.join('foo',dI))]
like image 41
jhoepken Avatar answered Oct 03 '22 09:10

jhoepken


You can use os.walk() in various ways

(1) to get the relative paths of subdirectories. Note that '.' is the same value you get from os.getcwd()

for i,j,y in os.walk('.'):
    print(i)

(2) to get the full paths of subdirectories

for root, dirs, files in os.walk('path'):
    print(root)

(3) to get a list of subdirectories folder names

dir_list = []
for root, dirs, files in os.walk(path):
    dir_list.extend(dirs)
print(dir_list)

(4) Another way is glob module (see this answer)

like image 26
Avinash Raj Avatar answered Oct 03 '22 10:10

Avinash Raj


Just use os.path.isdir on the results returned by os.listdir, as in:

def listdirs(path):
    return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
like image 37
Frerich Raabe Avatar answered Oct 03 '22 11:10

Frerich Raabe


That should work :

my_dirs = [d for d in os.listdir('My_directory') if os.path.isdir(os.path.join('My_directory', d))]
like image 43
coincoin Avatar answered Oct 03 '22 10:10

coincoin