Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get number of subfolders and folders using Python os walks?

Tags:

python

What I have a directory of folders and subfolders. What I'm trying to do is get the number of subfolders within the folders, and plot them on a scatter plot using matplotlib. I have the code to get the number of files, but how would I get the number of subfolders within a folder. This probably has a simple answer but I'm a newb to Python. Any help is appreciated.

This is the code I have so far to get the number of files:

import os
import matplotlib.pyplot as plt

def fcount(path):
    count1 = 0
    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
            count1 += 1

    return count1

path = "/Desktop/lay"
print fcount(path)
like image 231
mikez1 Avatar asked Nov 02 '13 22:11

mikez1


3 Answers

import os

def fcount(path, map = {}):
  count = 0
  for f in os.listdir(path):
    child = os.path.join(path, f)
    if os.path.isdir(child):
      child_count = fcount(child, map)
      count += child_count + 1 # unless include self
  map[path] = count
  return count

path = "/Desktop/lay"
map = {}
print fcount(path, map)

Here is a full implementation and tested. It returns the number of subfolders without the current folder. If you want to change that you have to put the + 1 in the last line instead of where the comment is.

like image 93
Danyel Avatar answered Oct 05 '22 11:10

Danyel


I think os.walk could be what you are looking for:

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)

This will walk give you the number of directories in the given path.

like image 42
dnf0 Avatar answered Oct 05 '22 11:10

dnf0


Try the following recipe:

import os.path  
import glob  
folder = glob.glob("path/*")
len(folder)
like image 30
behnam heidary Avatar answered Oct 05 '22 12:10

behnam heidary