Python | Sort and store files with the same extension



Take a look at the image shown below — 

This folder is completely disorganized. If you are prompted to find a specific file in that folder (or perhaps a larger folder with thousands of files), you will be stuck and completely overwhelmed. It can be very difficult (even impossible) to find a file from this ocean of clutter. This problem can be solved with Python with a few lines of code. Let`s see how we can do that.

Below is the Python implementation —

Output:


import os

import shutil

 
# Write the name of the directory here
# what to sort

path = `/ path / to / directory`

 

 
# This will create a well-organized
# list with all filenames
# there in the directory

list_ = os.listdir (path)

 
# This will go through every file

for file_ in list_:

name, ext = os.path.splitext (file_)

  

  # This will store the extension type

ext = ext [ 1 :]

 

# This triggers the next iteration,

  # if it`s a directory

  if ext = = ``:

continue

 

# This will move the file to the

# where the name is & # 39; ext & # 39; already exists

if os.path .exists (path + `/` + ext):

shutil.move (path + `/` + file_, path + `/` + ext + `/` + file_)

 

# This will create a new directory,

  # if the directory does not already exist

< code class = "undefined spaces">  else :

  os.makedirs (path + ` / ` + ext)

shutil.move (path + `/` + file_, path + ` / ` + ext + `/ ` + file_)