I am relatively new to bash. I wanted to know if there was an existing command on Mac OS' terminal to seperate video files by month in new directories. Essentially, this means that if I have videos in a span of 12 months, I would have 12 new directories with the videos put inside.
Otherwise, I was wondering if there was another way I could do this maybe through python to solve such problem.
I was hoping to use this to work with 500+ video files. It would tremendously help me if I could just have a script doing it for me instead of going through them one by one.
Before Script
After Script(Desired Output)
Update (found the solution)
I ended up finding the solution thank you for leading me to the right answer. Now I learnt one new thing today
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
You can write a python script that does it for you.
Use os
module to get information about your files. Especially creation time:
import os
r = os.stat("path/to/file")
print(r.st_ctime_ns) # it prints the number of nano seconds since creation (Windows OS)
In order to get the list of files/directories in a directory, you can use os
module too:
os.listdir("path/to/directory/") # you get a list of all files/directories
In order to convert the timestamp into a datetime, you can use datetime
module:
from datetime import datetime
d = r.st_ctime_ns // 1000000 # convert to seconds
date = datetime.fromtimestamp(d)
print(date) ## datetime.datetime(2019, 3, 19, 5, 37, 22)
print(date.year) ## get the year
print(date.month) ## get the month
print(date.day) ## get the day
Now you have just to compbine these information to organize your files.
os.mkdir("directory name")
os.rename("old path", "new path")