如何利用Python批量重命名照片

暗香疏影 创作者

当我们有很多照片的时候,有的照片使用A相机,有的使用B相机,很难分类。于是使用Python重命名照片,即可通过读取照片属性获得相机型号和拍照时间来分类。

安装Python和使用PyChram编译器

Python的安装在这里并不想多少,目前网络上的教程都是正确的。
自从用了PyChram的编译器,世界更加美好了。编译环境可以根据每个项目不一样而不同。
下载地址:https://www.jetbrains.com/pycharm/

安装必要组件

安装依赖,在Terminal安装:

1
2
pip install Pillow 
pip install exifread

Python由ChatGPT写

代码测试

运行以下代码测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from PIL import Image
import os
import exifread
from datetime import datetime

def get_exif_date_and_camera(file_path):
with open(file_path, 'rb') as image_file:
tags = exifread.process_file(image_file, stop_tag='EXIF DateTimeOriginal')
if 'EXIF DateTimeOriginal' in tags:
date_taken = tags['EXIF DateTimeOriginal']
date_taken = datetime.strptime(str(date_taken), '%Y:%m:%d %H:%M:%S')
else:
# Use file creation time if EXIF date is not available
date_taken = datetime.fromtimestamp(os.path.getctime(file_path))

# Extract camera make and model information
camera_make = str(tags.get('Image Make', 'Unknown'))
camera_model = str(tags.get('Image Model', 'Unknown'))

return date_taken, camera_make, camera_model

def rename_photos(directory):
for filename in os.listdir(directory):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
file_path = os.path.join(directory, filename)

date_taken, camera_make, camera_model = get_exif_date_and_camera(file_path)

# Format the new filename
new_filename = f"{date_taken.strftime('%Y%m%d_%H%M%S')}_{camera_make}_{camera_model}.jpg"
new_filepath = os.path.join(directory, new_filename)

# Rename the file
os.rename(file_path, new_filepath)
print(f"Renamed: {filename} to {new_filename}")

if __name__ == "__main__":
# Replace 'your_directory_path' with the path to your photos directory
photos_directory = 'X:\\AAA\\photo'
rename_photos(photos_directory)

本次教程结束。已发布到GitHub

  • 标题: 如何利用Python批量重命名照片
  • 作者: 暗香疏影
  • 创建于 : 2023-11-19 00:00:00
  • 更新于 : 2023-11-19 00:00:00
  • 链接: https://blog.pptcar.com/2023/11/19/2023-11-19-Python-Photo-Rename-based-Camera-Model/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
如何利用Python批量重命名照片