Created
April 4, 2020 05:47
-
-
Save yoonbae81/35069dac41d332ddfe1989cc2cb18309 to your computer and use it in GitHub Desktop.
파일명이 유사한 사진파일을 활용해 동영상 촬영일시를 추론하고 파일명 바꾸기
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
| from datetime import datetime | |
| from os import rename, walk | |
| from os.path import join, splitext, basename | |
| import exiftool | |
| def get_files(dir): | |
| files = [] | |
| for d, _, fs in walk(dir): | |
| for f in fs: | |
| filepath = join(d, f) | |
| files.append(filepath) | |
| return files | |
| def get_metadata(files): | |
| with exiftool.ExifTool('exiftool.exe') as et: | |
| metadata = et.get_tags_batch(['SourceFile', 'EXIF:CreateDate'], files) | |
| return metadata | |
| def parse(metadata): | |
| output = {} | |
| for item in metadata: | |
| filepath = item['SourceFile'] | |
| try: | |
| created = datetime.strptime(item['EXIF:CreateDate'], '%Y:%m:%d %H:%M:%S') | |
| timestamp = int(created.timestamp()) | |
| except KeyError: | |
| print('No EXIF:' + filepath) | |
| timestamp = 0 | |
| output[filepath] = timestamp | |
| return output | |
| def ren(filepath, timestamp): | |
| orig = filepath | |
| orig_name = splitext(basename(orig))[0] | |
| new_name = datetime.strftime(datetime.fromtimestamp(timestamp), '%Y%m%d %H%M%S') | |
| new = orig.replace(orig_name, new_name) | |
| new = new.replace(splitext(new)[1], splitext(new)[1].lower()) | |
| rename(orig, new) | |
| pictures = get_files("D:\\test\\pictures") | |
| metadata = get_metadata(pictures) | |
| with_timestamp = parse(metadata) | |
| movies = get_files("D:\\test\\movies") | |
| without_timestamp = {filepath: 0 for filepath in movies} | |
| merged = {**with_timestamp, **without_timestamp} | |
| sorted(merged.items(), key=lambda item: basename(item[0])) | |
| year = 2019 | |
| prev = min([item[1] for item in merged.items() if item[1] > datetime(year, 1, 1).timestamp()], ) | |
| datetime.fromtimestamp(prev) | |
| for path, timestamp in sorted(merged.items(), key=lambda item: basename(item[0])): | |
| if timestamp == 0: | |
| without_timestamp[path] = prev | |
| else: | |
| prev = timestamp | |
| for path, timestamp in without_timestamp.items(): | |
| print(f'{path} has {datetime.fromtimestamp(without_timestamp[path])}') | |
| for path, timestamp in without_timestamp.items(): | |
| while True: | |
| try: | |
| ren(path, timestamp) | |
| except FileExistsError: | |
| print('Duplicated:' + path) | |
| timestamp += 1 | |
| continue | |
| break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment