20
Create an automated file formator with python
we will going to create an automated file formator with python
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
â 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.
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
20