DjarumX
DjarumX

Reputation: 25

Return number of folders in directory and subdirectory

I have a directory similar the example down below which contains the following folders:

C:\Users\xx\Desktop\New folder\New folder\New folder\QGIS
C:\Users\xx\Desktop\New folder\New folder\New folder (2)\1- QGIS
C:\Users\xx\Desktop\New folder\New folder\New folder (4)\1.0 QGIS
C:\Users\xx\Desktop\New folder\New folder\QGIS

I wish to find how many folders with their names ends in QGIS and their path.

My current script is down below. It successfully gives me the path of all folders name ends in QGIS but the script counts only the folders with name "QGIS" only and doesnt count "1.0 QGIS" or "1- QGIS". What am I missing?

import os

rootfolder = r'C:\Users\xx\Desktop\New folder'

isfile = os.path.isfile
join = os.path.join

i=0

with open("folderpath.txt", 'w') as f:

    for root, dirs, files in os.walk(rootfolder, topdown=False):
        i+= dirs.count('*QGIS')
        for name in dirs:
            if name.endswith("QGIS"):
                f.write(os.path.join(root, name)+'\n')

    f.write(str((sum(dirs.count('QGIS') for _, dirs, _ in os.walk(rootfolder)))))

Upvotes: 0

Views: 132

Answers (2)

user14243928
user14243928

Reputation:

import os

print( len( list( filter(None, map(lambda x: x[0] if x[0].endswith('QGIS') else None,os.walk('.'))))))

A shorter form, but not too readable ;) The "map" goes through the results of os.walk, returns the folder name if it ends with 'QGIS' and None if not. The "filter" returns every value from map's results which differ from value None. The "list" is needed, because both map and filter are returning an iterator object, which has no length, but the "list" has.

Upvotes: 0

alani
alani

Reputation: 13049

The list.count method does not support any concept of a wildcard -- it just looks for how many elements are equal to the value that is given as an argument. So your line

        i+= dirs.count('*QGIS')

is looking for directories which are literally called *QGIS, rather than directories that end with QGIS.

The fix here should be easy because the code is already successfully printing out the correct paths; it is just not counting them correctly. So all that you need to do is to remove the above statement, and instead just add 1 in the place where you print out each path, which is already subject to the correct if condition inside the loop over directory names.

    for root, dirs, files in os.walk(rootfolder, topdown=False):
        for name in dirs:
            if name.endswith("QGIS"):
                f.write(os.path.join(root, name)+'\n')
                i += 1

You already correctly initialise i=0 before the start of the loop.

At the end, just do:

print(i)

and get rid of that expression involving sum where you walk through all the directories a second time.

Upvotes: 1

Related Questions