DEV Community

Guru prasanna
Guru prasanna

Posted on

Python Weekend Tasks

Task:1
Consider you have many photos in a folder. Check their Properties. In Properties, you have created date. Move all photos which have specific Created Date to a different folder.

import os
import shutil
import datetime

source_folder = r"/home/guru/Desktop/Guru/Python/images"

destination_folder = r"/home/guru/Desktop/Guru/Python/images2"

target_date = "2025-01-11"

os.makedirs(destination_folder, exist_ok=True)

for file_name in os.listdir(source_folder):
    file_path = os.path.join(source_folder, file_name)

    if os.path.isfile(file_path):
        created_time = os.stat(file_path).st_mtime
        created_date = datetime.datetime.fromtimestamp(created_time).strftime("%Y-%m-%d")

        if created_date == target_date:
            shutil.move(file_path, os.path.join(destination_folder, file_name))
            print(f"Moved: {file_name}")

print("Task completed.")
Enter fullscreen mode Exit fullscreen mode

Image description

Summary:
1) Imports Required Modules → Uses os for file handling, shutil for moving files, and datetime for date formatting.

2) Defines Source and Destination Folders → Specifies where the images are stored and where they should be moved.

3) Sets Target Date → Filters files based on their last modified date (formatted as YYYY-MM-DD).

4) Creates Destination Folder If It Doesn’t Exist → Ensures the folder is available before moving files.

5) Loops Through Files in the Source Folder → Checks each file one by one.

6) Extracts the Last Modified Date → Converts the file’s last modified timestamp into a human-readable format.

7) Compares the File's Date with the Target Date → If they match, the file is selected for moving.

8) Moves the File to the Destination Folder → Transfers matching files to the specified location.

9) Prints Status Messages → Displays which files were moved and confirms completion.

Top comments (0)