DEV Community

Cover image for Python Script to Organize Files in Folders
Akash Senta
Akash Senta

Posted on

Python Script to Organize Files in Folders

Python is really easy and fun language which can help us to build small scripts to automate some of our work. Here while reading few articles i came across one script written in python that help us to organize files in one folder ex. Downloads Folder where we download everything. To search a particular file from such mess was tedious task, but here my friend python can automate your task and help you to keep organised your downloads directory. Let's go ahead check below script.

import os
import shutil

#The Path of the directory to be sorted
path = 'C:\\Users\\<USERNAME>\\Downloads'
#This populates a list with the filenames in the directory
list_ = os.listdir(path)

#Traverses every file
for file_ in list_:
    name,ext = os.path.splitext(file_)
    #Stores the extension type
    ext = ext[1:]
    #If it is directory, it forces the next iteration
    if ext == '':
    #If a directory with the name 'ext' exists, it moves the file to that directory
    if os.path.exists(path+'/'+ext):
    #If the directory does not exist, it creates a new directory
Enter fullscreen mode Exit fullscreen mode

You can save above mentioned file with and mentioned Path variable as your Directory which you want to organize in my case i wanted to organize my downloads directory. What this script will do is look for certain extensions in files and make directory with name of extensions of not present and move files in particular directory. Let’s Run file with below command

Alt Text

Originally Posted : Akash Senta's Blog

Top comments (1)

angelosorte profile image

Thanks! It worked greatly!!! :D