DEV Community

Alfie Torres
Alfie Torres

Posted on

Organising Cat Videos using Python

Alt Text

After learning Python yesterday, I thought that It would be best to solidify my learning by building something useful. One issue I had over the week involved compiling around 500+ videos for my kittens birthday celebration. After organising the first 10 videos by month, I was already fed up.

Alt Text

To my attention, I realised that I could actually make a script in python to go through these videos much faster. Using the GetFileInfo -d yourfile.mov, I realised that I could actually get the unique month and year that the file was created in.

Alt Text

Now, comes the part where I have to use Python


import os, shutil 
from datetime import datetime

filepath = "/Users/alfietorres/Downloads/"      #base file path 
for filename in os.listdir(filepath):           #iterate through each file in the directory

    r = os.stat(filepath+filename)              #look for the file path and the file name
    d = r.st_birthtime                          #look for the time created 
    date=datetime.fromtimestamp(d)              #assign the details to a date variable

    month_directory = filepath+str(date.month)+"-"+str(date.year)      #use the date variable to create a UNIQUE new directory 
    file_being_moved = filepath+filename        #file the path of the file being moved    

    if os.path.isdir(month_directory) :         #check if the directory is created
        print("directory found ... ")
        shutil.move(file_being_moved,month_directory)   #move the file we are iterating on to the directory
    else: 
        print("creating directory ... ")        
        os.mkdir(month_directory)                       #create new directory 
        shutil.move(file_being_moved,month_directory)   #move items in new directory

Enter fullscreen mode Exit fullscreen mode

Essentially, we have a for each loop going through each file in the downloads directory.

Afterwards, we find the month-year of that file and check if has already been created.

If the new directory has already been created, then all we have to do is move the file.

If it has not been created then we will create a new directory and move the file into that directory.

After running the file, we get the following output (voila). Now you have an organised list of new directories. You can even add new videos in the Downloads directory and run the script again to reorganise the files.

Alt Text

Top comments (0)