a5_1.py

def count_extensions(dir_name):
	"""Print the count of different file suffixes in a folder."""
	import os
	from os.path import splitext
	# suffix_count is our histogram (key=suffix, value=count).
	suffix_count = dict()
	# os.walk returns a "generator" which we can treat like a list.
	# Elements of the list are 3-tuples of form (directory path,
	# list of subdirectories, list of files).
	# Note that we do not need to deal with subdirectories explicitly.
	for root, dirs, files in os.walk(dir_name):
		for name in files:
			base, ext = splitext(name)
			if ext == "":
				continue
			suffix_count[ext] = suffix_count.get(ext, 0) + 1
	# "iterkeys" is the same as "keys" except it returns an iterator
	# instead of a real list (very similar to generators).
	# Using iterators is better if there are many elements in the
	# dictionary because Python does not have to construct a large list.
	# In Python 3, there is no "iterkeys" because "keys" returns a
	# "view" rather than a real list, so there is no performance penalty.
	#
	#for suffix in sorted(suffix_count.keys()):
	for suffix in sorted(suffix_count.iterkeys()):
		print suffix, '\t', suffix_count[suffix]

count_extensions(".")