DEV Community

Sunil Aleti
Sunil Aleti

Posted on

Python script for Sorting Files w.r.t Filetype Extensions

GitHub logo aletisunil / sort-files-with-same-extension

A python script which sorts the files with respect to file type extension


We download many files from internet and whatever file type it may be, all files will be downloaded and located in 'Downloads' folder. And it looks like a clutter.
So today we will see, how to sort files with respect to filetype extension i.e mp4,docx,pdf,exe etc
And we can use python script to sort files with respect to filetype extension

Step 1:
In order to workaround we need some modules, and we can import them using 'import' keyword

  • os // allows you to interface with the underlying operating system
  • shutil // responsible for copying nd moving files respectively
  • glob // used to retrieve files/pathnames matching a specified pattern

Step 2:
so with the help of glob module, we retrive all files present in that pathlocation

ex: filename=glob.glob("C:/Users/Aleti Sunil/Downloads/*")
Enter fullscreen mode Exit fullscreen mode

Step 3:
we will create lists with respect to filetype extensions

documents=['.pdf','.docx','.doc','.txt']
media=['.jpeg','.jpg','.svg','.png','.PNG','.mp4','.mp3']
setupFiles=['.exe','.msi']
compressedFiles=['.zip']
files=['.apk']
Enter fullscreen mode Exit fullscreen mode

And specify the path locations of documents,media and setupfiles respectively

DocumentsLocation='C:/Users/Aleti Sunil/Downloads/documents'
mediaLocation='C:/Users/Aleti Sunil/Downloads/media'
setupFilesLocation='C:/Users/Aleti Sunil/Downloads/setupFiles'
compressedFilesLocation='C:/Users/Aleti Sunil/Downloads/compressedFiles'
FilesLocation='C:/Users/Aleti Sunil/Downloads/Files'
Enter fullscreen mode Exit fullscreen mode

Step 4:
And this is the final step, we will extract the filetype extension using 'os.path.splitext' and moves the files with respect to filetype extension to specified location

And this is final code

import os
import glob
import shutil
from os import path
filename=glob.glob("C:/Users/Aleti Sunil/Downloads/*")
documents=['.pdf','.docx','.doc','.txt']
media=['.jpeg','.jpg','.svg','.png','.PNG','.mp4','.mp3']
setupFiles=['.exe','.msi']
compressedFiles=['.zip']
files=['.apk']
DocumentsLocation='C:/Users/Aleti Sunil/Downloads/documents'
mediaLocation='C:/Users/Aleti Sunil/Downloads/media'
setupFilesLocation='C:/Users/Aleti Sunil/Downloads/setupFiles'
compressedFilesLocation='C:/Users/Aleti Sunil/Downloads/compressedFiles'
FilesLocation='C:/Users/Aleti Sunil/Downloads/Files'
for file in filename:
    if os.path.splitext(file)[1] in documents:
        if(path.exists(DocumentsLocation)):
            shutil.move(file,DocumentsLocation)
        else:
            os.mkdir(DocumentsLocation)
            shutil.move(file,DocumentsLocation)
    if os.path.splitext(file)[1] in media:
        if(path.exists(mediaLocation)):
            shutil.move(file,mediaLocation)
        else:
            os.mkdir(mediaLocation)
            shutil.move(file,mediaLocation)
    if os.path.splitext(file)[1] in setupFiles:
        if(path.exists(setupFilesLocation)):
            shutil.move(file,setupFilesLocation)
        else:
            os.mkdir(setupFilesLocation)
            shutil.move(file,setupFilesLocation)
    if os.path.splitext(file)[1] in compressedFiles:
        if(path.exists(compressedFilesLocation)):
            shutil.move(file,compressedFilesLocation)
        else:
            os.mkdir(compressedFilesLocation)
            shutil.move(file,compressedFilesLocation)
    if os.path.splitext(file)[1] in files:
        if(path.exists(FilesLocation)):
            shutil.move(file,FilesLocation)
        else:
            os.mkdir(FilesLocation)
            shutil.move(file,FilesLocation)
Enter fullscreen mode Exit fullscreen mode

A demo video on how it works

Let me know, if any queries
Happy Coding ❤️

Top comments (1)

Collapse
 
voyeg3r profile image
Info Comment hidden by post author - thread only accessible via permalink
Sérgio Araújo • Edited

I am thinking of how to create a more generic method and apply a kind of decorator to perform this action, but for now, it is just an idea.

I think the first step is to get the varible names to transform them, like documents to DocumentsLocation. In python 3 to get the variable name we can do: f'{documents=}'.split('=')[0]

I have already done this: variable = f'{x=}'.split('=')[0].title() + 'Location'
some research here: stackoverflow.com/a/58451182/2571881

In fact I have done this:

#!/usr/bin/env python
# coding: utf-8

from pathlib import Path
downloads = Path.home() / 'Downloads/'

for f in downloads.iterdir():
    if f.is_file():
        name, ext = f.name, f.suffix[1:]
        p = Path(downloads) / f'{ext}_files'
        p.mkdir(parents=True, exist_ok=True)
        Path(f).rename(p / f'{f.name}')

With a little StackOverflow help: stackoverflow.com/a/52774612
It can be improved to separate file families but for now what it does is: It creates folders like:

mp3_files, doc_files, iso_files and so on

Another idea is to use python to get file metadata an read the type from the files itselves. Today I have found this:

>>> import mimetypes
>>> import os
>>> for f in os.listdir('.'):
...     print(mimetypes.guess_type(f))
...

Some comments have been hidden by the post's author - find out more