Organize Your Chaotic Files with Ease: Introducing a Python File Sorter

·

3 min read

Table of contents

Have you ever struggled with cleaning your desktop and found it hectic to arrange files and folders or arrange files in their relevant folders? Well, I struggle with this after every few weeks and I am too lazy to arrange them. So today I thought why not write a Python script that can help me arrange files to their relevant folders? (send the files with the same extension to one folder.) I ended up writing this script which anybody can run just copy this to the messy folder and it will work like a charm.

import os
import shutil
for item in os.listdir():
    ex=item.split('.')
    src=os.getcwd()+'/'+item
    if(len(ex)>1 and item!="sort.py"):
        dst=os.getcwd()+'/'+ex[-1]+'/'
        if os.path.exists(dst):
            shutil.move(src,dst)
        else:
            os.mkdir(dst)
            shutil.move(src,dst)

Breakdown:

we will be using two libraries for this first one is OS second one is shutil. OS will help us find the file paths and directories and create new directories for new data types. Shutil will help us with moving files to their relevant folders.

  1. The condition for the loop is for item in os.listdir(): os.listdir() returns a list with the name of all the files and folders we take that list and we iterate through it.

  2. Second, we split the item at the point of '.' so one part is the name of the file and the second is the extension.

  3. Thirdly, we create the source path of the file os.getcwd() getcwd() kind of means get-current-working-directory(). so we get the current directory. and we concatenate the string with the item(file name) to create a source path.

  4. Then, we check if the length of the list ex if(len(ex)>1): that we split is greater than 1 or no this is to check if it is a folder or a file. if it is a file it would be split based on the '.' and its length would be greater than 1 if it could not be split means it is a folder so we do not need to move it.

  5. Then, We check if the folder for that extension exists or not with os.path.exists(os.getcwd()+'/'+ex[-1]+'/') remember ex[-1] has the extension and ex[0] has the file name so we check with ex[-1] because we are trying to check if a folder for the specific file type exists or not.

  6. if it exists then we can can move forward with moving the files to the relevant folder.

  7. if it does not exist we can move forward with creating the directory(folder) of the relevant file type and then we proceed forward with moving the file in it. os.mkdir(dst) creates a new directory with the relevant path. and moves the file into it.

After sorting your actual folder will look like this

You can copy it from here or you can directory download the executable version of this script from my GitHub link.