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
    for suffix in sorted(suffix_count.keys()):
        print("{suffix}\t{count}".format(suffix=suffix,
                                         count=suffix_count[suffix]))

count_extensions(".")