Jump to content

Photo Soter - Python

Tigerbomb8

Hey guys,

I am almost finished on it just need to fix a few thing and add a few features but i thought i should post it here. Please give me any advice or criticism that you feel you help me.

 

The program in question will rename a photo to the time and date is was taken based on the EXIF data, then move it to a new location, where it will be put in subfolder based on its year and month.

It took only 7.5 seconds for it to process 2856 images.

 

Requires EXIFread (pip install exifread)

I can't give much more information right now.. It is 5 in the morning and i got to hit the hay.

 

Better place to view the code: https://gist.github.com/PvtHaggard/7406c60beea302adc355

__author__ = "Pvt_Haggard"__version__ = "0.3" # TODO: Create function to search all sub-folders in the old directory import osimport exifreadimport timeimport sys  def sorter(old_directory, new_root_directory):	print "Sorting"	successful = 0	file_list = os.listdir(old_directory)	print "{} files".format(len(file_list))	for a_file in file_list:		try:			# Get required EXIF data			image = open("%s\\%s" % (old_directory, a_file), "rb")			tags = exifread.process_file(image, details=False, stop_tag="EXIF DateTimeOriginal")			image.close() 			make_sub_folders(new_root_directory, str(tags["EXIF DateTimeOriginal"]))			month, year = get_month_and_year(str(tags["EXIF DateTimeOriginal"]))			new_image_name = format_date_and_time(str(tags["EXIF DateTimeOriginal"]))						copy_number = 1			while True:				# Rename and move image				try:					os.rename("{}\\{}".format(old_directory, a_file),							  "{}\\{}\\{}\\{}_({}){}".format(new_root_directory, year, month, new_image_name,															 copy_number, os.path.splitext(a_file)[1].lower()))					successful += 1					break				except OSError:					copy_number += 1		except KeyError:			pass			# print "Extension %s is not compatible" % (os.path.splitext(a_file)[1])	print "{} images processed".format(successful)  def make_sub_folders(dir, date_time):	months = {"01": "January", "02": "February", "03": "March", "04": "April", "05": "May", "06": "June",	          "07": "July", "08": "August", "09": "September", "10": "October", "11": "November", "12": "December"}	try:		os.makedirs("{}\\{}\\{}".format(dir, date_time[0:4], months[date_time[5:7]]))	except OSError, e:		pass  def get_month_and_year(date_time):	months = {"01": "January", "02": "February", "03": "March", "04": "April", "05": "May", "06": "June",	          "07": "July", "08": "August", "09": "September", "10": "October", "11": "November", "12": "December"}	month = months[date_time[5:7]]	year = date_time[0:4]	return month, year  def format_date_and_time(date_time):	# Convert that data in to correct format	months = {"01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "June",	          "07": "July", "08": "Aug", "09": "Sept", "10": "Oct", "11": "Nov", "12": "Dec"}	date = date_time[0:date_time.find(' ')]                         # Separates the date from date_time	date = "%s-%s-%s" % (date[8:10], months[date[5:7]], date[2:4])  # Reformats the date to dd-month_abbreviation-yy	time = date_time[date_time.find(' ') + 1:]                      # Separates the time from date_time	time = "%s-%s" % (time[0:2], time[3:5])                         # Reformats the time to hh-mm	# Converts time from 24 hour into 12 hour	if 12 < int(time[0:2]) < 22:		time = "0{}-{}pm".format(str(int(time[0:2]) - 12), time[3:5])	elif int(time[0:2]) >= 22:		time = "{}-{}pm".format(str(int(time[0:2]) - 12), time[3:5])	elif int(time[0:2]) == 12:		time = "{}pm".format(time)	elif int(time[0:2]) == 00:		time = "12-{}am".format(time[3:5])	else:		time = "{}am".format(time)	return "{} {}".format(time, date)  def main():	# Final name format is HH-MMam DD-month_abbreviation-YY_(n)	# n will increase if two images have the same time and date 	print "This program will take photos from their current location and then rename and move them to a new location, this location is a subfolder based on their year and month taken."	print "Their must not be any subfolders in the current photo location. (I know how to fix this)\n" 	print "Example paths:"	print "Current photo location - C:\User\UserName\Pictures\Messy"	print "New photo locations - C:\User\UserName\Pictures\Sorted\n" 	old_directory = "D:\\old"	new_root_directory = "D:\\new"	#old_directory = raw_input("Please enter photos original directory path: ")	#new_root_directory = raw_input("Please enter photos new directory path: ") 	print "Warning: this program may cause loss of files. Use at you own risk."	print "Move and rename images from {} to {}, this cannot be undone".format(old_directory, new_root_directory)	accept = 'y'	accept = raw_input("Continue? Enter y or n: ")	if accept.lower() == 'y':		start = time.time()		sorter(old_directory, new_root_directory)		print time.time() - start main()

CPU: i7 4770k | GPU: Sapphire 290 Tri-X OC | RAM: Corsair Vengeance LP 2x8GB | MTB: GA-Z87X-UD5HCOOLER: Noctua NH-D14 | PSU: Corsair 760i | CASE: Corsair 550D | DISPLAY:  BenQ XL2420TE


Firestrike scores - Graphics: 10781 Physics: 9448 Combined: 4289


"Nvidia, Fuck you" - Linus Torvald

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

I have not really done much Python but one thing that I saw immediately was that you are recreating the "months" array(not sure if it is called an array in python) multiple times. You could just make it one global variable seeing as it does not change. 

 

I just looked up a python list. Maybe that is a better way to do it? 

months=[1,2,3,4,5,6]

Just replace the numbers with the month names and use the index to get the month. You might need to add or subtract 1 to get the correct month

months[date_time - 1]

or something like that.

Link to comment
Share on other sites

Link to post
Share on other sites

If you use os.renames it will create the missing directories for you, so you could get rid of the make_sub_folders function.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×