Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count and print number of files in subfolders using Python

My folder structure is as follows
Folder A
Folder B1
Folder B2
....
Folder Bn

How can I count the number of files in each of the folders (Folder B1 - Folder Bn), check if the number of files is larger than a given limit and print the folder name and number of files in it on the screen?

Like this:
Folders with too many files:
Folder B3 101
Folder B7 256

Here's what I've tried so far. It goes through every subfolder in each of my Folder B1 etc. I just need file count in one level.

import os, sys ,csv
path = '/Folder A/'

outwriter = csv.writer(open("numFiles.csv", 'w')

dir_count = []

for root, dirs, files in os.walk(path):
    for d in dirs:
        a = str(d)
        count = 0
        for fi in files:
            count += 1
        y = (a, count)
        dir_count.append(y)

    for i in dir_count:
        outwriter.writerow(i)

And then I just printed numFiles.csv. Not quite how I'd like to do it. Thanks in advance!

like image 427
selveste Avatar asked Oct 30 '14 11:10

selveste


1 Answers

As the are all contained in that single folder, you only need to search that directory:

import os
path = '/Folder A/'
mn = 20
folders = ([name for name in os.listdir(path)
            if os.path.isdir(os.path.join(path, name)) and name.startswith("B")]) # get all directories 
for folder in folders:
    contents = os.listdir(os.path.join(path,folder)) # get list of contents
    if len(contents) > mn: # if greater than the limit, print folder and number of contents
        print(folder,len(contents)
like image 59
Padraic Cunningham Avatar answered Sep 21 '22 00:09

Padraic Cunningham