[리원아빠] 생성날짜, 수정날짜로 파일이름 일괄 변경하기 (파이썬)

2022. 3. 14. 10:03Python

반응형

파이썬으로 파일 이름을 생성날짜로 (수정날짜) 일괄 변경하기



사진정리를 하다가 사진 이름도 나만의 포맷으로 관리를 하고자 하는 욕구가 생겼다.

그래서 이 프로그램을 만들었다.

 

소스폴더와 타켓폴더를 만들고 소스폴더에는 원본사진을,

그리고 타켓폴더에는 변경된 이름의 사진이 저장되도록 했다.

사진의 생성날짜는 메타정보를 읽어왔으며 메타정보가 없을 경우엔

파일 자체의 생성시간을 읽어오도록 했다.

 

사진파일도 확장자가 여러종류이기에 확장자 역시 변수에 저장을 해놨다가

이름 변경 후에도 동일한 확장자를 다시 붙여주었다.

대표적인 확장자인 jpeg, jpg, png, mp4, exe등을 테스트 했을 경우 문제없이 잘 작동했다.

 

하지만 작업을 하면서 추가적인 문제가 발견되었고 이를 해결하기 위해 2번의 수정이 필요했다.

발견한 문제는 아래와 같다. 

  • 문제1: 실제 파일의 생성날짜는 2019년인데 다운로드, 복사, 편집등으로 생성날짜가 2022년으로 갱실될 때
    • 해결1: 생성날짜와 수정날짜 두가지 정보를 읽어와 더 이전값으로 이름을 변경함
  • 문제2: 생성날짜와 촬영일짜가 다른 파일 존재 (사진파일일 경우에만)
    • 해결2: 생성날짜, 수정날짜, 촬영날짜 세가지 정보를 읽어와 가장 작은 값으로 이름을 변경

 

최종적으로 완성된 코드를 첨부한다.

코드를 사용하고자 한다면 환경에 맞게 file_src, file_tar 변수만 설정하면 된다.

 

import os
import datetime
import shutil
from PIL import Image

#작업할 경로 변수 (윈도우 경우에도 폴더 구분자를 '\'가 아닌 '/'로 해야한다)
file_src = 'C:/Users/root/PycharmProjects/pythonProject/img_source/'
file_tar = 'C:/Users/root/PycharmProjects/pythonProject/img_target/'
cnt = 0 #시간,분,초 같은 파일 존재하므로 구분을 위해

file_list = os.listdir(file_src)    #폴더로 이동하여 파일 리스트 추출

for file in file_list : #source 파일 리스트 읽어오기
    old_name = file_src+file    #기존 이름 확인
    ext = os.path.splitext(file)[1] #파일 확장자 확인
    create_time = str(datetime.datetime.fromtimestamp(os.path.getctime(file_src+file)))  #생성시간 추출
    modify_time = str(datetime.datetime.fromtimestamp(os.path.getmtime(file_src+file)))  #수정시간 추출

    # 년월일시간분초.확장자 포맷으로 정제 ex)20200105161500.jpg
    create_time = create_time.replace('-', '')
    create_time = create_time.replace(':', '')
    create_time = create_time.replace(' ', '')
    create_time = create_time[0:15]  # 생성시간경우 밀리세컨드까지 포함해 자리수 맞춤이 필요함
    modify_time = modify_time.replace('-', '')
    modify_time = modify_time.replace(':', '')
    modify_time = modify_time.replace(' ', '')
    modify_time = modify_time[0:15]

    #사진일 경우 촬영날짜도 추출
    try:
        pic = Image.open(file_src+file)
        meta = pic._getexif()
        take_pic_time = meta[36867] #사진촬영시간 추출
        take_pic_time = take_pic_time.replace('-', '')
        take_pic_time = take_pic_time.replace(':', '')
        take_pic_time = take_pic_time.replace(' ', '')
        take_pic_time = take_pic_time[0:15]
    except Exception:   #찍은 날짜가 존재하지 않을 경우 현재시간으로 세팅하여 가장 큰값이되어 선택되는 일 없도록 함
        take_pic_time = datetime.datetime.now()
        take_pic_time = datetime.datetime.strftime(take_pic_time,'%Y%m%d%H%M%S')
        take_pic_time = take_pic_time.replace('-', '')
        take_pic_time = take_pic_time.replace(':', '')
        take_pic_time = take_pic_time.replace(' ', '')
        take_pic_time = take_pic_time[0:15]

    time_list =[take_pic_time, create_time, modify_time]
    time_list.sort() #세가지 시간 중 가장 오래된 시간 선택을 위해 정렬
    
    #가장 오래된 시간을 new_name으로 설정
    new_name = file_tar+time_list[0]+'_'+str(cnt)+ext
    shutil.copy2(old_name, new_name)    # 파일 복사 후 이름 변경
    cnt += 1    #구분자 값 증가

print ('원본갯수: ' +str(len(file_list)) +'\n변경갯수: ' +str(cnt))

 

그럼 끝.

반응형