← 목록으로

Python으로 사진 EXIF 정보를 활용하여 날짜별로 자동 분류하기

사진이 수천 장 쌓이다 보면 원하는 사진을 찾기 어려워집니다. 특히 스마트폰이나 카메라로 촬영한 사진들은 촬영 날짜 정보가 EXIF 메타데이터에 저장되어 있어 이를 활용하면 자동으로 날짜별 폴더에 정리할 수 있습니다. 이번 강좌에서는 Python으로 사진 파일의 EXIF 태그를 읽고, 촬영 날짜 기준으로 폴더를 생성하여 자동 분류하는 프로그램을 만들어보겠습니다.

1. EXIF란 무엇인가?

EXIF(Exchangeable Image File Format)는 사진에 저장되는 메타데이터입니다.

대표적으로 다음과 같은 정보가 포함됩니다.

  • 촬영 날짜/시간
  • 카메라 모델명
  • 렌즈 정보
  • GPS 위치 정보
  • 촬영 설정(ISO, 조리개 등)

예시:

DateTimeOriginal : 2024:07:15 14:32:11
Model            : iPhone 15 Pro
GPSLatitude      : 37.5665
GPSLongitude     : 126.9780
pip install pillow

Pillow는 Python에서 이미지를 다루기 위한 대표적인 라이브러리입니다.

3. EXIF 정보 읽기

먼저 한 장의 사진에서 EXIF 정보를 확인해 보겠습니다.

from PIL import Image
from PIL.ExifTags import TAGS

image_path = "test_image/20250117_103910.jpg"

image = Image.open(image_path)
exif_data = image.getexif()

for tag_id, value in exif_data.items():
    tag = TAGS.get(tag_id, tag_id)
    print(f"{tag}: {value}")

실행 결과:

4. 촬영 날짜만 추출하기

사진 정리를 위해서는 날짜 정보만 있으면 됩니다.

from PIL import Image
from PIL.ExifTags import TAGS

def get_photo_date(image_path):
    try:
        image = Image.open(image_path)
        exif_data = image.getexif()

        for tag_id, value in exif_data.items():
            tag = TAGS.get(tag_id, tag_id)

            if tag == "DateTime":
                return value

    except Exception as e:
        print(f"오류 발생 : {e}")

    return None


date = get_photo_date("test_image/20250117_103910.jpg")
print(date)

출력:

5. 날짜 형식 변경

폴더명을 만들기 쉽게 변환합니다.

from datetime import datetime

date_string = "2025:01:17 10:39:10"

dt = datetime.strptime(
    date_string,
    "%Y:%m:%d %H:%M:%S"
)

folder_name = dt.strftime("%Y-%m-%d")

print(folder_name)

출력:

6. 사진 자동 분류 프로그램 만들기

이제 지정된 폴더의 모든 사진을 읽어 날짜별로 정리해 보겠습니다.

예시 구조

실행 후

원본사진
 ├─ 2025-01-12
 │   └─ 20250112_122640.jpg
 │
 └─ 2025-01-05
     └─ 20250115_073544.jpg

7. 전체코드

import os
import shutil
from datetime import datetime

from PIL import Image
from PIL.ExifTags import TAGS


SOURCE_DIR = r"D:\Project\Python\Photo\test_image"


def get_photo_date(image_path):
    """
    EXIF에서 촬영 날짜 추출
    """
    try:
        image = Image.open(image_path)
        exif_data = image.getexif()

        for tag_id, value in exif_data.items():
            tag = TAGS.get(tag_id)

            if tag == "DateTime":
                return value

    except Exception as e:
        print(f"EXIF 읽기 실패: {image_path}")
        print(e)

    return None


def organize_photos():
    image_extensions = (
        ".jpg",
        ".jpeg",
        ".png"
    )

    for filename in os.listdir(SOURCE_DIR):

        if not filename.lower().endswith(image_extensions):
            continue

        file_path = os.path.join(SOURCE_DIR, filename)

        photo_date = get_photo_date(file_path)

        if not photo_date:
            print(f"날짜 정보 없음: {filename}")
            continue

        try:
            dt = datetime.strptime(
                photo_date,
                "%Y:%m:%d %H:%M:%S"
            )

            folder_name = dt.strftime("%Y-%m-%d")

            target_dir = os.path.join(
                SOURCE_DIR,
                folder_name
            )

            os.makedirs(target_dir, exist_ok=True)

            target_path = os.path.join(
                target_dir,
                filename
            )

            shutil.move(
                file_path,
                target_path
            )

            print(
                f"{filename} -> {folder_name}"
            )

        except Exception as e:
            print(e)


if __name__ == "__main__":
    organize_photos()

8. EXIF가 없는 사진 처리하기

인터넷에서 저장한 이미지나 메신저로 전송된 사진은 EXIF가 제거되는 경우가 많습니다.

이 경우 파일 생성일을 사용하도록 개선할 수 있습니다.

import os
from datetime import datetime


def get_file_date(file_path):
    timestamp = os.path.getmtime(file_path)

    return datetime.fromtimestamp(
        timestamp
    ).strftime("%Y-%m-%d")

적용 예시

if photo_date:
    dt = datetime.strptime(
        photo_date,
        "%Y:%m:%d %H:%M:%S"
    )
else:
    dt = datetime.fromtimestamp(
        os.path.getmtime(file_path)
    )

9. 년/월 기준으로 정리하기

사진 수가 많은 경우 하루 단위보다 월 단위가 관리하기 쉽습니다.

folder_name = dt.strftime("%Y-%m")

결과

Photos
 ├─ 2024-01
 ├─ 2024-02
 ├─ 2024-03
 └─ 2024-04

또는

folder_name = dt.strftime("%Y/%m")

결과

Photos
 ├─ 2024
 │   ├─ 01
 │   ├─ 02
 │   └─ 03

10. 마무리

이번 강좌에서는 Pillow 라이브러리를 이용하여 EXIF 정보를 읽고 DateTimeOriginal 태그를 추출한 뒤, 촬영 날짜를 기준으로 사진을 자동 분류하는 프로그램을 만들어 보았습니다.