Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    AWS

    Building a serverless web application with Python and AWS Lambda

    Java

    Spring Cloud Config Refresh Strategies

    React Native

    Build Real-World React Native App #4 : Content Placeholder

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Saturday, November 29
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Python / Automating and Scheduling Tasks Using Python
    Beginners

    Automating and Scheduling Tasks Using Python

    UsamaBy UsamaOctober 19, 2020No Comments9 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Automating and Scheduling Tasks Using Python
    This article Automating the boring Stuff: Scheduling Tasks using Python
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    This article Automating the boring Stuff: Scheduling Tasks using Python
    This article Automating the boring Stuff: Scheduling Tasks using Python

    Python is an interpreted, high-level, cross-platform, and easy-to-use programming language. Currently, it is one of the most powerful programming languages used in back-end web development, software development, artificial intelligence, machine learning, data processing, image processing, automation etc. We can automate almost everything on our system using the Python programming language. In this article, we will automate and schedule some tasks on our system using python.

    Why Automating Tasks

    In real life, there are some tasks that are not too difficult but time taking and it feels too much hard to complete those tasks manually. For example, renaming hundreds of files in a directory manually, organizing files in a directory, creating a backup of your files regularly, etc. These tasks are really time taking and you can save that much time by automating these tasks. There are many similar examples and we can make them easier by automating them. Saving time, increasing efficiency and increasing accuracy are the main reasons to automate tasks.

    Important Python Automation Modules

    There are a lot of automation modules in python. We can use these modules to automate almost everything on our system. We can use the ‘os’ module to manipulate our system like creating or deleting directories or files etc. System commands can also be run using this module. ‘Pyautogui’ is a module used to automate tasks related to keyboard and mouse. We can find screen resolution, move the pointer to a specific point, press any key, even drag and drop files using this module. Similarly, we can use the ‘time’ module to manipulate almost everything related to time. We can convert date and time to any format and use it in our program. ‘PIL’ is the module used to process images in python. We can read, crop, rotate, flip, and change the size of images using the ‘PIL’ module. We can even change the color scheme of an image from RGB to black and white using this module. In this article, we will discuss some use cases of automation using python which will involve some of the above modules.

    Automating Tasks Using Python

    In this section of the article, we will discuss some use cases in which python is used to automate some tasks on your system.

    Automatically Deleting Files that are not Accessed for Last 30 Days

    Let you have a lot of files in your downloads directory. Some of them are really important and you access them every two or three days and out of them, some are unnecessary. You want to delete those unnecessary files. This task will be easy and can be done manually if you have five to ten files in the downloads directory. But what if you have hundreds of files in your downloads directory? It will be a very difficult and time taking process to delete unnecessary files manually. You can make this process easy by automating this task.

    We will automate this task in such a way that all those files that are not accessed for the last thirty days will be deleted and the remaining files will remain the same. First of all, open python by typing the following command in the terminal,

    ubuntu@ubuntu:~$ python

    Now import required modules and go to the downloads directory using the ‘os’ module

    >>> #importing os module and time module
    >>> import time
    >>> import os
    >>> #moving to the downloads directory. Path to downloads directory will change depending upon your OS
    >>> os.chdir(‘/home/ubuntu/Downloads’);

    Now save a list of all the files and folders present in the downloads directory in a variable called lists.

    >>> #saving a list of all the files and folders in a variable
    >>> files = os.listdir(os.getcwd());

    Get the current time and also find the number of seconds in thirty days.

    >>> #getting current time and number of seconds in thirty days
    >>> present_time = time.time()
    >>> days = 30*24*60*60

    Now we will check each file one by one whether it is a file or a directory. If the item is a directory then we will take no action on it and if the item is a file then we will check when it was accessed last time. If the file was accessed within the last thirty days, then we will take no action on it otherwise we will delete it.

    >>> #applying for loop on ‘files’ variable
    >>> for file_name in files:
    . . .   #checking if the item is file or directory
    . . .   if not os.path.isdir(file_name):
    . . .     #getting last access time of file
    . . .     access_time = os.stat(file_name).st_atime
    . . .     #checking if the file was accessed within last 30 days
    . . .     if access_time < (present_time - days):
    . . .       #removing file which is not accessed for last 30 days
    . . .       os.remove(file_name)
    . . .       print(file_name + ‘ removed’)

    The above code, whenever you run, will automatically check all the files in the downloads directory and remove those files that are not accessed for the last thirty days.

    Read More:  7 Concepts: Why Your SVG Is the Way It Is

    NOTE: Use this function with care as files removed will not go to the recycle bin and hence can not be restored.

    Organizing Files in Download Directory Using System Commands in Python

    In this section of the article, we will automate another task and for this task, we will use system commands in python instead of using python’s commands. We will use system commands of Ubuntu and if you are using Windows operating system then some commands will be a little bit different.

    Let you have a lot of files in your download directory and you want to organize them in such a way that all the files with the same extension like (.pdf .docx etc) go to a single directory. Open python by typing the following command in the terminal,

    ubuntu@ubuntu:~$ python

    First of all, import the required module and go to download directory,

    >>> #importing required module
    >>> import os
    >>> #moving to Downloads directory
    >>> os.chdir(‘/home/ubuntu/Downloads’)

    Now note all the files and directories in a list named ‘files’

    >>> #saving the names of all the files and directories
    >>> files = os.listdir(os.getcwd())

    Now check each item whether it is a file or a directory. Skip all the directories and for each file, check the extension and move it to the corresponding directory. If the corresponding directory does not exist, then create a directory then move the file to the directory

    >>> #checking each file
    >>> for file_name in files:
    . . .  #checking if item is not directory
    . . .  if not os.path.isdir(file_name):
    . . .    #checking if file is pdf
    . . .    if file_name.endswith(‘.pdf’):
    . . .      #checking if pdf directory does not exist
    . . .      if not os.path.isdir(‘pdf’):
    . . .        #creating pdf directory using system command
    . . .        os.system(‘mkdir pdf’)
    . . .      #moving pdf file to pdf directory using system command
    . . .      os.system(‘mv ’+file_name+’ ./pdf/’)
    . . .    #checking if file is png
    . . .    elif file_name.endswith(‘.png’):
    . . .      #checking if images directory exists
    . . .      if not os.path.isdir(‘images’):
    . . .        #creating images directory using system command
    . . .        os.system(‘mkdir images’)
    . . .      #moving png file to images folder using system command
    . . .      os.system(‘mv ‘+file_name+’ ./images/’)

    Scheduling Python Scripts Using Crontab

    So far we have written scripts to automate some tasks using python. Now What about executing python scripts automatically? Python scripts will not be executed automatically, we will have to execute them manually. We can schedule python scripts to execute automatically after a specific time using crontab.

    Read More:  The Ultimate Guide to Pip

    If we want these python scripts to run automatically every week so we will schedule it using crontab as follows. Open crontab in editing mode by typing the following command in the terminal,

    ubuntu@ubuntu:~$ crontab -e

    It will open a file and put the following line in the bottom of the file

    0 0 * * 0 python [path_to_python_script]

    The first entry in the above line is for minutes and it ranges from 0 to 59. The second entry is for hours which ranges from 0 to 23. The third entry is used to describe the day of the month and its range is from 1 to 31. The fourth entry is used to specify the month and its range is from 1 to 12. We can also use JAN, FEB, etc for the month. The fifth and the last entry is used to describe the day of the week and its range is from 0 to 6 with Sunday being 0. We can also specify the day of the week by using short names of the day like SAT, SUN, etc.

    After these entries come to the command which we want to run. In this case, we want to schedule our python scripts so we will run the above command. The Python script used in this cron job will run every week at 00:00. You can further get a deeper knowledge about scheduling tasks using crontab by visiting the following link https://crontab.guru/.

    Automating and scheduling your tasks can make life easier by saving time and increasing efficiency. In this article, we have used different use cases of automating tasks using python. We discussed two examples of automation in this article but you can use this knowledge to automate some other tasks. It is not everything but you can get the idea of automation using a programming language. You can also automate anything using system commands in python.

     

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Usama

      Related Posts

      Flask Development Made Easy: A Comprehensive Guide to Test-Driven Development

      January 4, 2024

      Creating Our Own Chat GPT

      July 27, 2023

      The Ultimate Guide to Pip

      June 12, 2023
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Programming October 7, 2016

      17. Уроки Node.js. Таймеры, Отличия от Браузера, ref и unref

      Всем привет! Эта статья посвящена таймерам в Node.js. В ней мы постараемся в первую очередь рассказать о тех различиях, которые есть между таймерами в браузерах и в Node.js.

      Уроки React. Урок 1, Введение.

      September 5, 2016

      Interview with Andrei

      September 11, 2017

      Effective Strategies for Managing Project Risks Successfully

      December 1, 2024

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Fortune 500 top hiring trends in 2019. How big corporations hire top talents?

      JavaScript September 24, 2018

      13. Уроки Node.js. Разработка, supervisor

      Programming September 21, 2016

      Conquering Imposter Syndrome: Empowering Startup Founders

      Startups December 16, 2024

      How to Upload Images to a Cloud Storage(Imgur) in an Angular Application

      Angular January 13, 2020

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Programming

      The Impact of Integrated Development Environments on Programming

      React

      Understanding Data-binding in React and Angular

      Programming

      12. Уроки Node.js . Документация Http Модуля.

      Most Popular

      Crafting an Effective Marketing Strategy for Your Startup

      Startups

      How to send multiple forms with Ajax (FormData) in Django

      Python

      Why Using Node.js for Developing Web Applications Makes Perfect Sense

      JavaScript
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.