批量更改照片视频文件名

#! /usr/bin/python3
# vim: ts=8 sw=8 noexpandtab
# Usage: rename image by exif date or created file date

import sys, os
import argparse
import shutil
import datetime, time
from PIL import Image
import pytz
from win32com.propsys import propsys, pscon

# args
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--folder', required=True)
parser.add_argument('-d', '--date', action='store_true', help='get date from folder name')
argv = parser.parse_args()

# global var
duplicates = ['00000000_000000_0']
count = 0


def do(pathname):
	global count
	if os.path.isdir(pathname):
		count = 0
		for f in sorted(os.listdir(pathname)):
			do(os.path.join(pathname, f))
	else: # file
		fname = pathname
		fext  = os.path.splitext(fname)[-1]
		new_name = ''
		count += 1

		if argv.date is True:	# rename by folder date string
			f = os.path.basename(os.path.dirname(fname))
			new_name = '%s_%03d' % (f[:8], count)
		elif fext in ['.mp4', '.MOV', '.AVI']:
			try: # need full path
				properties = propsys.SHGetPropertyStoreFromParsingName(fname)
				dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
				properties = None # release file handle
				if dt is not None:
					if fext == '.mp4':
						dt = dt.astimezone(pytz.timezone('Asia/Shanghai'))
					new_name = dt.strftime('%Y:%m:%d %H:%M:%S')
			except Exception as e:
				new_name = ''
		else:
			try:
				img = Image.open(fname)
				if hasattr(img, '_getexif'):
					exif = img._getexif()
					if not exif is None:
						DateTimeOriginal = 36867
						for k,v in exif.items():
							if k == DateTimeOriginal:
								new_name = v
								break
				img.close()
			except Exception as e:
				new_name = ''

		if new_name == '':		# no exif, get file modified date
			mtime = os.path.getmtime(fname)
			new_name = datetime.datetime.fromtimestamp(mtime).strftime('%Y:%m:%d %H:%M:%S')

		new_name = new_name.replace(':', '').replace(' ', '_')

		# check if time is same second
		if duplicates[-1].startswith(new_name):
			new_name += '_' + str(int(duplicates[-1].split('_')[-1])+1)
			duplicates.append(new_name) 
		else:
			duplicates.clear()
			duplicates.append(new_name + '_0')
			
		# rename
		new_fname = os.path.join(os.path.dirname(fname), new_name + fext)
		if not os.path.isfile(new_fname):
			shutil.move(fname, new_fname)
		elif not new_fname == fname:
			new_fname = os.path.join(os.path.dirname(fname), new_name + '_' + str(count) + fext)
			shutil.move(fname, new_fname)
		print('%d:\t%s\t\t=> %s' % (count, fname, new_fname))
	
def print_exif(fname):
	img = Image.open(fname)

	if hasattr(img, '_getexif'):
		exif = img._getexif()
		if not exif is None:
			for (k, v) in exif.items():
				if isinstance(v, str):
					print('%s\t\t= %s' % (k, v))
	img.close()

if __name__ == '__main__':
	do(os.path.abspath(argv.folder))

 

    原文作者:imtank
    原文地址: https://blog.csdn.net/imtank/article/details/104127710
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞