Simple Python script to clean up your desktop

·

2 min read

We all know the problem that our desktop gets cluttered pretty quickly. So I decided to write a simple Python script that automatically cleans up my Deskop for me. I want to move music, text and pictures into a directory of my choice.

1. Make sure you have installed Python on your PC

If you haven't installed Python yet, you can download the latest version on: python.org/downloads

After you installed Python, open CMD and enter this command:

py

After that, you should see the currently installed version of python and the editor should open. You can then close it again with exit().

image.png

2. Directory preparation

Create three folders for music, text, and pictures in another folder of your choice.

image.png

3. Start Coding

First, create a .py file for the script. Then open that file in any Editor of your choice.

Importing the Modules: Now we are importing two modules:

  • os

  • shutil

     import os
     import shutil

Next, we declare the path variables:

desktop = 'path/to/your/Desktop/'
picdir = 'path/to/your/new/folder/pictures/'
musicdir = 'path/to/your/new/folder/music/'
textdir = 'path/to/your/new/folder/text/'

Don't forget the "/" after the last folder

Main Code

After that, we implement the main functionality of our script. I will explain these according to the code snippet.

for fname in os.listdir(desktop):
    if fname.endswith('.jpg') or fname.endswith('.png'):
        shutil.move(desktop+fname, picdir+fname)
        break
    elif fname.endswith('.mp3') or fname.endswith('.wav'):
        shutil.move(desktop+fname, musicdir+fname)
    elif fname.endswith('.txt'):
        shutil.move(desktop+fname, textdir+fname)
else:
      print('Desktop is clean!')

Explanation:

First we create a for loop which loops for all files (fname) in our desktop. Next, we have the if statement along with two else if blocks where we check even if its an picture, text or some music. If one of these "if's" are true, the file (desktop+fname= absolute path of the file) will be moved to the new directory (e.g. picdir+fname) with the shutil.move() method.

I hope you have learned something in this tutorial and have fun trying it by your self. For any questions or suggestions leave a comment.