DEV Community

Cover image for Automate the deletion of old screenshots.
Akshay Rao
Akshay Rao

Posted on

Automate the deletion of old screenshots.

Introduction
Hi, This is Akshay Rao, in my daily work life I have to take a lot of screenshot for documentation purpose.So, there were so many screenshots and had to delete only other days screenshots, so every day I had to delete them manually.
So, I thought of automating the deletion of screenshots at 5PM everyday.
In this blog will share how i did this.I hope this will help you also.
Lets's start

  • made a file name screenshot-deletion.py
  • we will have to know the path where all the screenshots are saved.
  • now identify the dates that are attached in the name of the screenshot.
  • Identify the dates first with regular expressions.
  • now one by one compare the date with the current date, then delete them.
import os
import re
from datetime import datetime

#set path where all the screenshots are saved
folder_path = "put/path/folder"

files = os.listdir(folder_path)
current_date = datetime.now().date()

#pattern for date to recognize
date_pattern=r"\d{4}-\d{2}-\d{2}"

#print(current_date)
#print(folder_path)

for file in files:
    file_path=os.path.join(folder_path, file)
    #print(file_path)
    if os.path.isfile(file_path):
        screenshots=re.search(date_pattern, file_path)
        if screenshots:
            if screenshots.group() != current_date:
                try:
                    print("removing this file:", file)
                    os.remove(file_path)
                except Exception as e:
                    print("cannot delete this file - {e}")
        else:
            print("screenshots don't exist")
Enter fullscreen mode Exit fullscreen mode
  1. edit the crontab -e
00 17 * * * /usr/bin/python3 /path/to/your/script.py
Enter fullscreen mode Exit fullscreen mode

i hope that this helps you by any means.
Thank you

Top comments (0)