1. 程式人生 > >利用python讀取照片拍攝時間來重新命名照片,方便組織和查詢

利用python讀取照片拍攝時間來重新命名照片,方便組織和查詢

使用iphone手機拍照後的照片名字是“IMG_數字.jpg”的命名規則,使用下面的指令碼可以將影象重新命名為“拍攝年月日_IMG_數字.jpg”的形式。

import os
import exifread

def getExif(path, filename):
    old_full_file_name = os.path.join(imgpath, filename)
    FIELD = 'EXIF DateTimeOriginal'
    fd = open(old_full_file_name, 'rb')
    tags = exifread.process_file(fd)
    fd.close()
    if FIELD in tags:
        new_name = str(tags[FIELD]).replace(':', '').replace(' ', '_') + os.path.splitext(filename)[1]
        tot = 1
        while os.path.exists(new_name):
            new_name = str(tags[FIELD]).replace(':', '').replace(' ', '_') + '_' + str(tot) + os.path.splitext(filename)[1]
            tot += 1

        new_name2 = new_name.split(".")[0][:8] + '_' +filename
        
        new_full_file_name = os.path.join(imgpath, new_name2)
        print(old_full_file_name," ---> ", new_full_file_name)    
        os.rename(old_full_file_name, new_full_file_name)
    else:
        print('No {} found'.format(FIELD),' in: ', old_full_file_name)
        

imgpath = "D:\\105APPLE\\"
for filename in os.listdir(imgpath):
    full_file_name = os.path.join(imgpath, filename) 
        
    if os.path.isfile(full_file_name):
       getExif(imgpath, filename)
       #print(full_file_name)