Skip to content

Instantly share code, notes, and snippets.

@elisboa
Created May 16, 2021 21:37
Show Gist options
  • Save elisboa/907e67dcd7c3d252cb697d10cf5aeead to your computer and use it in GitHub Desktop.
Save elisboa/907e67dcd7c3d252cb697d10cf5aeead to your computer and use it in GitHub Desktop.
Sort Files in python
#!/usr/bin/env python3
### WARNING CODE IS INCOMPLETE
# NEED TO PUT ARGUMENT PARSING ON A TRY/CATCH STRUCTURE
# Sortfiles is a simple script that reads the creation date of a JPG or CR2 file, creates a directory structure of Year/Month/Day and then moves it to this destation directory.
# Libs
import os
from datetime import datetime
import sys
import subprocess
### Vars
global ORIGIN_PATH
global DESTIN_PATH
global Full_File_Path
global File_Year
global File_Month
global File_Day
global File_CreateDate
### Functions
def getFile_Year(File_CreateDate):
return(str(File_CreateDate.split("-", 4)[0]))
def getFile_Month(File_CreateDate):
return(str(File_CreateDate.split("-", 4)[1]))
def getFile_Day(File_CreateDate):
File_Day=str(File_CreateDate.split("-", 4)[2])
File_Day=str(File_Day[0] + str(File_Day[1]))
return(File_Day)
def moveFile(File, ORIGIN_PATH, DESTIN_PATH, File_Year, File_Month, File_Day):
Full_File_Path=DESTIN_PATH + "/" + File_Year + "/" + File_Month + "/" + File_Day
os.system("echo mkdir -p %s" % Full_File_Path)
print ("Trying to create directory " + Full_File_Path, end = " ")
subprocess.call(['echo', 'mkdir', '-p', 'Full_File_Path'])
print ("OK!")
print ("Moving file " + File + " to " + Full_File_Path, end = " ")
subprocess.call(['echo', 'mv', File, Full_File_Path])
print ("OK!")
def parsefile(file):
print ("Parsing file " + File)
File_CreateDate=os.stat(File).st_ctime
File_CreateDate=str((datetime.fromtimestamp(File_CreateDate)))
print ("Created at " + File_CreateDate)
File_Year=getFile_Year(File_CreateDate)
print("Year: " + File_Year)
File_Month=getFile_Month(File_CreateDate)
print("Month: " + File_Month)
File_Day=getFile_Day(File_CreateDate)
print("Day: " + File_Day)
moveFile(File, ORIGIN_PATH, DESTIN_PATH, File_Year, File_Month, File_Day)
#
##
### Main code
print ("Welcome to " + sys.argv[0] + "!")
print("Arguments passed: " + str(sys.argv))
print ("Listing files...", end = " ")
if len(sys.argv) < 2:
print("Usage: " + sys.argv[0] + " ORIGIN_PATH " + " DESTINATION_PATH")
else:
ORIGIN_PATH=str(sys.argv[1])
DESTIN_PATH=str(sys.argv[2])
Files = os.listdir(ORIGIN_PATH)
print ("OK!")
for File in Files:
if File.endswith(".JPG"):
parsefile(File)
if File.endswith(".CR2"):
parsefile(File)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment