You all know how much messy it looks when all files lying on a single folder. like this 👇🏻
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
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.
step 3
→ Now create a function for folders making
step 4
→ make a function for moving files to folders
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
Top comments (0)