Homework: Counting File Types

Counting file types

The following code lists all the extensions (e.g. .pdf or .doc) of any files in your Downloads folder (replace with the folder of your choice).

import os

for filename in os.listdir('/Users/YOUR_USERNAME/Downloads'):
    pieces = filename.split('.')
    print(pieces)
    extension = pieces[-1]
    print(extension)

Using this code and a Python dictionary, count how many files you have of each file type. E.g. 5 pdfs, 7 docs, etc.

Try it out on different directories on your machine. Some files might not have a type extension at all, figure out how to count those as their own "no extension" type.

Extension 1:

Programatically figure out which filetype is the most common in this directory and print it out at the end: E.g. The most common file type in this directory are pdfs with 7 in total.

Extension 2:

Directories don't have extensions (normally) so your code would be counting them as "no extension" types. Fix your code so that you count directories separately. E.g. your dictionary should look similar to:

YOURDICT = {
    'pdf': 42,
    'js': 4,
    'py': 2,
    'directory': 4
}

Hint: The os module has a way to check whether a path is a directory or not.

Last updated