Python practice: find how many files of each type (extension) exist in a given directory

#! usr/bin/env python3
# by lorenzo - 02/10/2017
# how many files of each type (extension) exist in a given directory?

import os, sys, operator

print("Enter directory where you want to search in:")
location = input()

if not os.path.isdir(location):
    print("You have to enter the address of a directory!")
    sys.exit()

myExt = {}

for folderName, subfolders, filenames in os.walk(location):
    for filename in filenames:
        fileName, fileExt = os.path.splitext(os.path.join(folderName, filename))
        if fileExt in myExt:
            myExt[fileExt] += 1
        else:
            myExt[fileExt] = 1

# descending order based on number of files for each extension, remove reverse=True for ascending order
# if you want to sort based on names of extensions (alphabetical order), use key=operator.itemgetter(0)
myDict = sorted(myExt.items(), key=operator.itemgetter(1), reverse=True) 
for x in myDict:
    print("Extension: " + x[0] + "; number of files with this extension: " + str(x[1]))

Comments about the code are welcome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s