May-02-2019, 01:24 PM
I am making an image sorting program based on the date which the image was taken in which everything works perfectly except one thing. I know my code is very messy, but this is my first ever large program. I will post just a small part of it and try to explain. So, first of all, it tries to get all the image's properties using a previously defined function. It works fine and returns a dictionary of all the properties. If an error occurs, that filename is appended to a list called cant_sort. After that, it tries to get the date in which the image was taken. Not all the pictures have this, so if a KeyError occurs, it tries to get the last modification date. The rest of the code doesn't matter for my question. The problem is that most of the files which don't have the date in which image was taken, slip into the cant_sort list. But I want them to go into thesort_by_mod dictionary. I am thinking that I should arrange the try and except statements differently. I want to note, that everything else works perfectly and there are no other errors. Also if I should post the full code in order to locate the problem, I can do that. Thanks in advance.
import shutil def get_date(fn): ret = {} i = Image.open(fn) info = i.getexif() for tag, value in info.items(): decoded = TAGS.get(tag, tag) ret[decoded] = value return ret for file in images: try: all_data = get_date(file) try: taken_date = all_data['DateTimeOriginal'].replace(" ", ":") taken_date = taken_date.split(":") list_dates = list(taken_date[0:3]) if str(list_dates) not in existing_dates: existing_dates[str(list(taken_date[0:3]))] = file if str(list_dates) in existing_dates: if file not in existing_dates[str(list_dates)].split(","): existing_dates[str(list_dates)] = (existing_dates[str(list_dates)] + "," + file) except KeyError: mod_date = all_data['DateTime'].replace(" ", ":") mod_date = mod_date.split(":") list_dates = list(mod_date[0:3]) if str(list_dates) not in sort_by_mod: sort_by_mod["m"+str(list(mod_date[0:3]))] = file if str(list_dates) in sort_by_mod: if file not in sort_by_mod[str(list_dates)].split(","): sort_by_mod[str(list_dates)] = (sort_by_mod[str(list_dates)] + "," + file) except: cant_sort.append(file)