Create an automated file formator with python

Create an automated file formator with python

ยท

1 min read

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)

Take a look on the output

ย