Using Python to sort the mess in your folders

  • Makes a folder for every extension present in the folder
  • Moves the files to their respective folders
  • Shutil — for moving or copying the files
import os
import shutil

# path directory to be sorted
path = '/Users/anubhavtomar/Desktop/'
# listing all the files to given path
list_of_file = os.listdir(path)
new_folder = []# loop through files extract name and extension separatelyfor i in list_of_file:
name, exta = os.path.splitext(i)
exta = exta[1:] #removes the period from extension

if exta == '': #to skip the folders

curr_dir = path #join makes the path with right slashes
fin_path = os.path.join(curr_dir, exta) # makes the path for the new extension folder
file_path = os.path.join(curr_dir, i) # makes path of current file

if os.path.exists(fin_path): # if extension folder exists, move
shutil.move(file_path, fin_path + '/' + i)
os.makedirs(fin_path) #if it doesnt exits, make it then move
shutil.move(file_path, fin_path + '/' + i)
print(f"folders are sorted by extension: {list_of_file}")



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Adding long tweets makes me nauseous.