Image sorter by created date in python
Question: I need to make a program that sort all the .jpg files in a directory, or
simply all the files in the directory(because they are all jpg, so it doesnt
have to be specifically fro jpgs) and that depending on the date they were
made, puts them in two separate folders: say for example before 2012 in one
folder, and after 2012 in the other....the thing that i dont know how to do is
how to i get the program to read through the properties of of all of the
files/.jpgs in the folder , after that i think i know what to do : store the
dates in a variable , create the two folders and then i was thinking of an if
statemente that transfers the files comparing their dates. But how do i tell
the program to do this for every file,no matter how many they are?...because i
dont know how many files there are in the folder. thanks!!!


Answer: Here is some quick code to get you in the right direction. It goes through all
files in a folder and moves them into two separate subfolders. You can modify
this to use modify-date instead of create-date, or to get just .jpg files if
you need.

    
    
    import os, datetime
    
    folder_name = "MY_PATH"
    for file_name in os.listdir(folder_name):
        file_name_full = os.path.join(folder_name, file_name)
        if not os.path.isfile(file_name_full):
            continue
        timestamp = os.path.getctime(file_name_full)
        dt = datetime.datetime.fromtimestamp(timestamp)
        # print out the datestamp
        print dt
    
        # if you now want to put them into subfolders based on the year 2012 
        # you can do something like the following
        yr = dt.year
        subfolder_name = ""
        if yr < 2012:
            subfolder_name = "before 2012"
        else:
            subfolder_name = "2012 and after"
        subfolder_name_full = os.path.join(folder_name, subfolder_name)
        new_file_name_full = os.path.join(subfolder_name_full, file_name)
        # I assume your folders are premade. If not, you can do a quick-and-dirty mkdir here
    
        print "Moving %s -> %s" % (file_name_full, new_file_name_full)
        os.rename(file_name_full, new_file_name_full)
    

