HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

2) More Data Types Lesson

Python Project: File Counter

4 min to complete · By Martin Breuss

Contents

  1. Introduction

In the previous module of this course, you wrote a script that was able to move all your screenshots from your messy desktop into a new folder. In this project, you'll revisit your file mover code and expand on it with the knowledge of some additional data types in order to make it more flexible and powerful.

When you built your file mover, you used the pathlib module that worked with Path() objects. You can consider Path() objects as yet another data type, one that is more custom and not considered a built-in type. As you might remember, you'll have to import it from the standard library in order to work with it.

In this project, you'll continue to work with pathlib and files, but you'll also use some of the additional built-in data types that you got to know in this section.

File Type Counter

Path() objects have an attribute called .suffix that allows you to get the file extension of each file that you're working with. You used it previously to decide which files are screenshots:

if filepath.suffix == '.png':
    pass  # Do something

Now, your desktop has gotten quite messy again, but this time, you want to know what's on there and what keeps cluttering it up!

To get that information, write a script that locates your Desktop, fetches all the files that are on there, and counts how many files of each different file type are on your desktop. Use a dictionary to collect this data, and print it to your console at the end in order to get an overview of what is there.

Colorful illustration of a light bulb

Info: You can use another package from the standard library called pprint, which stands for "pretty print", in order to display your output nicely formatted.

You can now expand on your file mover script and add logic that moves all file types that have, e.g., more than five files on the desktop into their own separate folder. Will it help to keep your desktop cleaner?

It could be interesting to keep track of what types of files keep agglomerating on your desktop in surprising numbers after you've cleaned it yet again. You wrote this script that counts them and shows you the counts as a dictionary, but you'll probably forget these numbers until the next time you run the script.

You could copy the dictionary and save it in a text document. But that sounds repetitive and also like something you might be able to automate using Python. In the next section, you'll learn about File Input/Output so you can write data to files and read it back from there.