Python | Sort and store files with same extension
Last Updated :
29 Dec, 2020
Have you ever wanted to find any particular file in a folder, but then completely freak out when you find that folder to be a hell of a mess? Well, Python is a rescue here.
Using Python OS-module and shutil module, we can organize the files with same extensions and store in separate folders.
Look at the image shown below –
This folder is fully unorganized. If you are told to find a particular file in this folder (or maybe an even larger folder with thousands of files), you will be stuck and become completely dumbstruck. It might be very tough (even impossible) to find a file from this ocean of mess. This problem can be solved using Python with a few lines of code. Let’s see how can we do this.
Below is the Python implementation –
import os
import shutil
path = '/path/to/directory'
list_ = os.listdir(path)
for file_ in list_:
name, ext = os.path.splitext(file_)
ext = ext[ 1 :]
if ext = = '':
continue
if os.path.exists(path + '/' + ext):
shutil.move(path + '/' + file_, path + '/' + ext + '/' + file_)
else :
os.makedirs(path + '/' + ext)
shutil.move(path + '/' + file_, path + '/' + ext + '/' + file_)
|
Output:
Share your thoughts in the comments
Please Login to comment...