fastApiProject/renamePhotoBatch.py

67 lines
2.1 KiB
Python
Raw Normal View History

2024-05-06 13:09:50 +08:00
#!/usr/bin/env python3
# @author 轩辕龙儿
# @date 2023/10/23
# @file renamePhotoBatch.py
import os
import glob
import exifread
2024-08-07 10:24:53 +08:00
import os.path, time
2024-05-06 13:09:50 +08:00
# 获取照片的拍摄时间
def get_photo_taken_time(image_path):
with open(image_path, 'rb') as f:
tags = exifread.process_file(f)
if 'EXIF DateTimeOriginal' in tags:
taken_time = tags['EXIF DateTimeOriginal']
return taken_time
else:
return None
2024-08-07 10:24:53 +08:00
def get_photo_update_time(image_path):
with open(image_path, 'rb') as f:
return time.ctime(os.stat(image_path).st_mtime)
2024-05-06 13:09:50 +08:00
def solution():
# 获取当前时间并格式化为年月日时分秒毫秒
# 设置照片所在的文件夹路径
2024-08-07 10:24:53 +08:00
# folder_path = "C:\\Users\\hyy\\Pictures\\图片"
folder_path = "C:\\Users\\hyy\\Pictures\\轩辕龙儿的文件收集20240803"
2024-05-06 13:09:50 +08:00
# 获取文件夹中的所有照片文件
2024-08-07 10:24:53 +08:00
# photo_files = glob.glob(os.path.join(folder_path, "*"))
photo_files = os.listdir(folder_path)
2024-05-06 13:09:50 +08:00
# 遍历照片文件并重命名
for photo in photo_files:
2024-08-07 17:25:08 +08:00
name = photo
photo = folder_path+"\\"+photo
creation_time_stamp = get_photo_taken_time(photo)
2024-05-06 13:09:50 +08:00
if creation_time_stamp is None:
continue
2024-08-07 17:25:08 +08:00
if name.startswith('IMG'):
file_name, file_ext = os.path.splitext(photo)
file_name = file_name[:-2]
os.rename(photo, f"{file_name}.jpeg")
2024-08-07 10:24:53 +08:00
continue
2024-05-06 13:09:50 +08:00
formatted_time = "IMG_" + creation_time_stamp.values.replace(':', '').replace(' ', '_')
file_name, file_ext = os.path.splitext(photo)
2024-08-07 10:24:53 +08:00
if file_name.startswith('.'):
file_name, file_ext = os.path.splitext(file_name)
2024-05-06 13:09:50 +08:00
new_file_name = f"{formatted_time}{file_ext}"
new_file_path = os.path.join(folder_path, new_file_name)
2024-08-07 10:24:53 +08:00
index = 1
while os.path.exists(new_file_path):
new_file_name = f"{formatted_time}-{index}{file_ext}"
new_file_path = os.path.join(folder_path, new_file_name)
2024-08-07 17:25:08 +08:00
index = index+1
2024-05-06 13:09:50 +08:00
os.rename(photo, new_file_path)
print("照片重命名完成!")
if __name__ == "__main__":
solution()