DEV Community

Cover image for Create an automated file formator with python
Sahil Saif
Sahil Saif

Posted on • Edited on

Create an automated file formator with python

You all know how much messy it looks when all files lying on a single folder. like this 👇🏻
0

we will going to create an automated file formator with python

step 1

we will use build-in os module
→ stores all files in a list with os.listdir( )
→ remove main python file in which we will working from the list
1

step 2

→ identifying file type and store them in their corresponding list
→ we are going to create 4 folders ( images, docs, media, others ) in which all the files will divided.
2

step 3

→ Now create a function for folders making
3

step 4

→ make a function for moving files to folders
4

Final code

import os

def createFolder(folder):
    if not os.path.exists(folder):
        os.makedirs(folder)

def moveToFolder(folder,fileName):
    for file in fileName:
        os.replace(file,f"{folder}/{file}")

files=os.listdir()
files.remove('main.py')

imgExt=[".img",".png",".jpeg"]
images=[file for file in files if os.path.splitext(file)[1].lower() in imgExt]

docExt=[".doc",".pdf",".txt"]
document=[file for file in files if os.path.splitext(file)[1].lower() in docExt]

mediaExt=[".mp4",".mp3"]
media=[file for file in files if os.path.splitext(file)[1].lower() in mediaExt]

others=[]
for file in files:
    ext=os.path.splitext(file)[1].lower()
    if (ext not in imgExt) and (ext not in docExt) and (ext not in mediaExt) and os.path.isfile(file):
        others.append(file)
createFolder("images")
createFolder("media")
createFolder("docs")
createFolder("others")

moveToFolder("images",images)
moveToFolder("media",media)
moveToFolder("docs",document)
moveToFolder("others",others)

Enter fullscreen mode Exit fullscreen mode

Take a look on the output

Top comments (0)