1. 程式人生 > 實用技巧 >python獲取照片的拍攝日期並重命名(遞迴命名一個資料夾下的所有照片)

python獲取照片的拍攝日期並重命名(遞迴命名一個資料夾下的所有照片)

# -*- coding: UTF-8 -*-
# python 3.9.0 64bit

import os
import exifread


def renamePic(dir):
    shootingTimeField = 'EXIF DateTimeOriginal'
    for root, dirs, files in os.walk(dir):
        for name in files:
            picName = os.path.join(root, name)
            fd = open(picName, 'rb')
            tags 
= exifread.process_file(fd) fd.close() if shootingTimeField in tags: info = str(tags[shootingTimeField]) newName = 'IMG_' + info[0:10] + '_' + info[11:11 + 8] + os.path.splitext(picName)[1] newName = newName.replace(':', '') newName
= os.path.join(root, newName) count = 1 while os.path.exists(newName): newName = 'IMG_' + info[0:10] + '_' + info[11:11 + 8] + '_' + str(count) + os.path.splitext(picName)[1] newName = newName.replace(':', '') newName
= os.path.join(root, newName) count += 1 os.rename(picName, newName) print('{} --> {}'.format(os.path.basename(picName), os.path.basename(newName))) else: print('pass: {}'.format(os.path.basename(picName))) if '__main__' == __name__: dir = input('Please input picture directory path which you want to rename: ') print() renamePic(dir) print() print('Done!') input('Press any key to exit!')