Last active
May 6, 2023 05:21
-
-
Save mcsmonk/117dee7d0bf481fcd1c6f99b1ce174b0 to your computer and use it in GitHub Desktop.
rename picture image file into YYYYMMDD_HHMMSS format using exif
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| 2023.03.16 | |
| rename picture image file into YYYYMMDD_HHMMSS format using exif | |
| All comments and almost the code is made by ChatGPT 3.5 | |
| 사진이 찍힌 시간을 이용하여 파일명을 (YYYYMMDD_HHMMSS)형태로 수정하는 코드 | |
| chatGPT 3.5를 이용해 만든 코드를 약간 수정함 | |
| 주석도 전부 ChatGPT가 작성함 | |
| """ | |
| import sys | |
| import os | |
| from PIL import Image | |
| from datetime import datetime | |
| import hashlib | |
| # 터미널에서 입력받은 경로를 가져옵니다. | |
| if len(sys.argv) < 2: | |
| print("Usage: python3 rename_files.py [path]") | |
| sys.exit(1) | |
| path = sys.argv[1] | |
| # 입력받은 경로가 존재하는지 확인합니다. | |
| if not os.path.isdir(path): | |
| print("Invalid directory path") | |
| sys.exit(1) | |
| # 디렉토리 내의 이미지 파일을 찾아서 파일명을 변경합니다. | |
| paths = os.listdir(path) | |
| paths.sort() | |
| print(paths) | |
| for filename in paths: | |
| if not filename.lower().endswith(('.jpg', '.jpeg', 'png')): | |
| continue | |
| print(filename, '-> ', end='') | |
| filepath = os.path.join(path, filename) | |
| # 파일을 바이너리 모드로 열어서 읽습니다. | |
| with open(filepath, "rb") as f: | |
| # 파일 내용의 해시값을 계산합니다. | |
| fhash1 = hashlib.sha256(f.read()).hexdigest() | |
| with Image.open(filepath) as im: | |
| # 이미지 파일의 Exif 정보에서 찍힌 시간을 가져옵니다. | |
| exif = im._getexif() | |
| if exif is None: | |
| print('passed') | |
| continue | |
| datetime_str = exif.get(36867) | |
| if datetime_str is None: | |
| print('passed') | |
| continue | |
| # datetime_str의 형식이 '%Y-%m-%d %H:%M:%S'일 경우 '%Y:%m:%d %H:%M:%S'로 변경합니다. | |
| datetime_str = datetime_str.replace('-', ':') | |
| datetime_obj = datetime.strptime(datetime_str, '%Y:%m:%d %H:%M:%S') | |
| # 새로운 파일명을 만듭니다. | |
| new_filename = datetime_obj.strftime("%Y%m%d_%H%M%S") + os.path.splitext(filename)[1] | |
| # 새로운 파일명이 이미 존재하는 경우 중복 처리 | |
| idx = 0 | |
| while os.path.exists(os.path.join(path, new_filename)): | |
| with open(os.path.join(path, new_filename), "rb") as f: | |
| fhash2 = hashlib.sha256(f.read()).hexdigest() | |
| if fhash1 == fhash2: | |
| break | |
| idx += 1 | |
| new_filename = f"{datetime_obj.strftime('%Y%m%d_%H%M%S')}_{idx}{os.path.splitext(filename)[1]}" | |
| # 파일명을 변경합니다. | |
| new_filepath = os.path.join(path, new_filename) | |
| os.rename(filepath, new_filepath) | |
| print(new_filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment