简体   繁体   中英

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

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)
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.

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.

Answering to:

how would I get the number of subfolders within a folder

You can use the os.path.isdir function similarly to os.path.isfile to count directories.

Try the following recipe:

import os.path  
import glob  
folder = glob.glob("path/*")
len(folder)

I guess you are looking for os.walk . Look in the Python reference, it says that:

os.walk(top, topdown=True, onerror=None, followlinks=False)

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple ( dirpath, dirnames, filenames ).

So, you can try to do this to get only the directories:

for root, dirs, files in os.walk('/usr/bin'):
    for name in dirs:
        print os.path.join(root, name)
        count += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM