Kevin Clark
Kevin Clark

Reputation: 21

How do you count subdirectories in a folder?

I figured out how to count directories in a folder, but not sure how I could edit my code to recursively count subdirectories. Any help would be appreciated.

This is my code so far.

def nestingLevel(path):
    count = 0
    for item in os.listdir(path):
        if item[0] != '.':
            n = os.path.join(path,item)
            if os.path.isdir(n):
                count += 1 + nestingLevel(n)
    return count

Upvotes: 2

Views: 2477

Answers (3)

wim
wim

Reputation: 362507

You can use a glob here - the ** pattern indicates a recursive glob. The trailing slash matches on directories, excluding other types of files.

from pathlib import Path

def recursive_subdir_count(path):
    dirs = Path(path).glob('**/')
    result = sum(1 for dir in dirs)
    result -= 1  # discount `path` itself

Using / works on windows, macOS, and Linux, so don't worry about putting os.sep instead.

Beware of a weird edge case: shell globs typically exclude hidden directories, i.e. those which begin with a ., but pathlib includes those (it's a feature, not a bug: see issue26096). If you care about discounting hidden directories, filter them out in the expression when calling sum. Or, use the older module glob which excludes them by default.

Upvotes: 3

zipa
zipa

Reputation: 27869

If you want to count them all without the root, this will do it:

len([i for i, j, k in os.walk('.')])-1

Upvotes: 1

R.F. Nelson
R.F. Nelson

Reputation: 2312

I think you may want to use os.walk:

import os

def fcount(path):
    count1 = 0
    for root, dirs, files in os.walk(path):
            count1 += len(dirs)

    return count1

path = "/home/"
print fcount(path)

Upvotes: 5

Related Questions