As anyone with a digital camera knows, you can generate a lot of files in a very short time from all of your photos. Since almost everyone in my household has a digital camera, that represents a lot of files, haphazardly scattered over many directories.
I’ve looked around quite a bit and found many utilities that will rename jpg files based on the date but they were rather unwieldy for the simple purpose that I had in mind: Rename a jpg file based on the EXIF date and time. That’s it. No viewing. No mp3’s. Just rename jpg files in the current directory.
Rolling up my sleeve, I used the pyexiv2 module for the metadata extraction and produced the following simple script:
import pyexiv2
import glob
import os
import string
import datetime
files = glob.glob('*')
for file in files:
if os.path.isfile(file):
try:
image = pyexiv2.Image(file)
image.readMetadata()
except:
print('File %s does not appear to have EXIF metadata' % (file,))
continue
try:
date_time = image['Exif.Image.DateTime']
except:
print('File %s does not appear to have date/time information in metadata' % (file,))
continue
possible_date_str = file.split("_")[0]
try:
datetime.datetime.strptime(possible_date_str, "%Y-%m-%dT%H:%M:%S")
except:
pass
else:
print("Skipping %s as it appears to already have the date/time in the filename" % (file,))
continue
newname = string.join([date_time.isoformat(),file],"_")
try:
print("Renaming %s to %s" % (file,newname))
os.rename(file,newname)
except:
print("Oops! Can't rename %s to %s" % (file, newname))
Of course it has no comments, no testing, etc. Feel free to improve.
Post a Comment