使用Python來整理相片

  • Post by
  • Mar 18, 2023
post-thumb

好課程介紹:
小孩學Python程式的入門課:http://bit.ly/TeachYourKidsToCode
大人學Python的進階課:https://bit.ly/100DaysOfCodePython

相片分類一直是很煩人的事,使用Python來解決這煩人的事吧!

Buy Me a Coffee

下列程式說明:

  • 通常電腦系統有幾種日期:修改日期及檔案建立日期等,要分類檔案通常使用修改日期。
  • src_dir:來源目錄
  • dest_dir:目的目錄
  • 將檔案放置於目的目錄dest_dir/yyyy/mm 例如 2023年02月的檔案會放置於 dest_dir/2023/02 目錄下
import os
import shutil
from datetime import datetime

src_dir = "/source/path"
dest_dir = "/dest/path"

if not os.path.exists(dest_dir):
    os.makedirs(dest_dir)

for root, dirs, files in os.walk(src_dir):
    for filename in files:
        src_filePath = os.path.join(root, filename)
        modified_timestamp = os.path.getmtime(src_filePath)
        modified_datetime = datetime.fromtimestamp(modified_timestamp)
        
        year_folder = os.path.join(dest_dir, str(modified_datetime.year))
        if not os.path.exists(year_folder):
            os.makedirs(year_folder)
        month_folder = os.path.join(year_folder, str("{:02d}".format(modified_datetime.month)))
        if not os.path.exists(month_folder):
            os.makedirs(month_folder)
        
        dest_filePath = os.path.join(month_folder, filename)

        if os.path.isfile(dest_filePath):
            new_filename, ext = os.path.splitext(dest_filePath)
            i = 1
            while os.path.isfile(f"{new_filename}_{i}{ext}"):
                i += 1
            dest_filePath = f"{new_filename}_{i}{ext}"
        else:
            dest_filePath = dest_filePath

        print("copy file_path:", src_filePath, " to: ", dest_filePath)
        shutil.move(src_filePath, dest_filePath)
LATEST POST
TAG