Automate your file manager using Python
Code:
import os # imports os module
import shutil # imports shutil module
file=os.listdir() # it lists the files present in this directory
def Createfolder(foldername): # Creates a foldername with a provided name
if not os.path.exists(foldername):# if folder does not exists
os.makedirs(foldername) # Then folder gets created of provided foldername
else:
print(f"{foldername} folder already exists") #if folder exists message gets printed
Createfolder('Media')
Createfolder('Documents')
Createfolder('Others')
# creating the extension list which contains photos videos
media=['.jpg','.png','.mp4']
for files in file:
# if the file extension is in media list
if os.path.splitext(files)[1].lower() in media:
try:
# Moves the images to the images folder by Provided path "E:\Microsoft VS Code\Python codes\Images"
shutil.move(files,"E:\Microsoft VS Code\Python codes\Media")
except:
# if the files are already moved the message gets displayed
print("Images are already moved ")
# creating the extension list of documents
docs=['.txt','.pptx','.pdf','.docx','.py']
for files in file:
if os.path.splitext(files)[1].lower() in docs: # if the file extension is in docs list
try:
# Move the Documents folder by Provided path "E:\Microsoft VS Code\Python codes\Documents"
shutil.move(files,"E:\Microsoft VS Code\Python codes\Documents")
except:
# if the files are already moved the message gets displayed
print("Images are already moved ")
for files in file:
#___if the extension is not in media and also not in docs list
if os.path.splitext(files)[1].lower() not in media and docs:
try:
# The files other than documents and images gets stored in the Others
folder by Provided path
"E:\Microsoft VS Code\Python codes\Others"
shutil.move(files,"E:\Microsoft VS Code\Python codes\Others")
except:
# if the files are already moved the message gets displayed
print("Images are already moved ")
Comments
Post a Comment