Buy Me a Coffee

使用Python來將檔案依據年份及月份分類

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

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

下列程式說明:

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

# specify the path to your files directory
src_dir = "/source/path"
dest_dir = "/dest/path"

# if dest_dir not exists, then create it
if not os.path.exists(dest_dir):
    os.makedirs(dest_dir)

# loop through all files in the directory
for root, dirs, files in os.walk(src_dir):
    for filename in files:
        src_filePath = os.path.join(root, filename)
        # get the creation date of the file
        modified_timestamp = os.path.getmtime(src_filePath)
        modified_datetime = datetime.fromtimestamp(modified_timestamp)
        
        # create a folder for the year and month if it doesn't exist
        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)
        
        # move the file to the appropriate folder
        dest_filePath = os.path.join(month_folder, filename)

        # check if the file exists
        if os.path.isfile(dest_filePath):
            # if the file exists, get a new name
            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:
            # if the file doesn't exist, use the original file path
            dest_filePath = dest_filePath

        print("copy file_path:", src_filePath, " to: ", dest_filePath)
        # shutil.copy(src_filePath, dest_filePath) you can use copy also
        shutil.move(src_filePath, dest_filePath)