Untitled

 avatar
unknown
plain_text
2 months ago
1.3 kB
14
Indexable
import os
import shutil
from datetime import datetime

def move_files_by_creation_year(source_dir, target_base_dir):
    # Walk through all directories and files in the source directory
    for root, dirs, files in os.walk(source_dir):
        for file_name in files:
            try:
                # Get full path of the file
                file_path = os.path.join(root, file_name)
                
                # Get the creation time of the file
                creation_time = datetime.fromtimestamp(os.path.getctime(file_path))
                year = str(creation_time.year)

                # Create the target directory if it doesn't exist
                target_dir = os.path.join(target_base_dir, year)
                os.makedirs(target_dir, exist_ok=True)

                # Move the file to the target directory
                shutil.move(file_path, os.path.join(target_dir, file_name))
                print(f"Moved '{file_name}' to '{target_dir}'")

            except Exception as e:
                print(f"Error processing {file_path}: {e}")

if __name__ == "__main__":
    source_directory = input("Enter the path of the source directory: ")
    target_base_directory = input("Enter the base path for the target directories: ")

    move_files_by_creation_year(source_directory, target_base_directory)
Editor is loading...
Leave a Comment