10 Python Automation Scripts to Simplify Your Tasks

Amit Bhargav
3 min readAug 7, 2023

Photo by Hitesh Choudhary on Unsplash

Introduction

- Briefly introduce the concept of automation and its importance in modern workflows.
- Highlight how Python is a popular choice for automation due to its versatility and ease of use.
- Mention that the blog post will cover 10 practical Python automation script ideas with code examples.

1. File Organizer

  • Describe the problem of cluttered files and the need for organizing them.
    - Explain how the script organizes files based on their types into separate directories.
    - Provide the code snippet and explain each part.
import os
import shutil

source_directory = '/path/to/source'
destination_directory = '/path/to/destination'

for filename in os.listdir(source_directory):
file_path = os.path.join(source_directory, filename)
if os.path.isfile(file_path):
file_extension = os.path.splitext(filename)[1]
target_directory = os.path.join(destination_directory, file_extension[1:])
os.makedirs(target_directory, exist_ok=True)
shutil.move(file_path, os.path.join(target_directory, filename))

2. Backup Script

  • Discuss the significance of regular backups for data safety.
    - Describe how the script automates the backup process.
    - Walk through the code example and highlight key components.
import shutil
import datetime

source_directory = '/path/to/source'
backup_directory = '/path/to/backup'

timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
backup_folder = os.path.join(backup_directory, f'backup_{timestamp}')

shutil.copytree(source_directory, backup_folder)

3. Social Media Post Scheduler

  • Explain the benefits of automating social media posts.
    - Introduce the concept of scheduling posts using Python.
    - Present the code snippet for scheduling social media posts.
import schedule
import time

def post_to_social_media():
# Add code to post to social media here
print("Posted to social media")

schedule.every().day.at("12:00").do(post_to_social_media)

while True:
schedule.run_pending()
time.sleep(1)

4. Email Sender

  • Discuss scenarios where automating emails can be useful.
    - Introduce the script that sends customized emails to recipients.
    - Break down the code for sending emails using the `smtplib` library.
import smtplib
from email.mime.text import MIMEText

def send_email(subject, message, recipients):
sender_email = 'your_email@example.com'
sender_password = 'your_password'

msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = ', '.join(recipients)

with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, recipients, msg.as_string())

subject = 'Automated Email'
message = 'This is an automated email sent from Python.'
recipients = ['recipient1@example.com', 'recipient2@example.com']

send_email(subject, message, recipients)

5. Download Manager

  • Highlight the convenience of automating file downloads.
    - Describe how the script downloads files from URLs.
    - Provide the code example and explain its functionality.
import requests

def download_file(url, destination):
response = requests.get(url)
with open(destination, 'wb') as f:
f.write(response.content)

url = 'https://example.com/somefile.txt'
destination = '/path/to/destination/somefile.txt'

download_file(url, destination)

6. Data Scraping Bot

  • Introduce web scraping as a way to automate data collection.
    - Explain how the script scrapes data from websites using `BeautifulSoup`.
    - Present the code snippet and discuss the parsing process.
import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Add code to parse and process the HTML data here

7. System Monitoring

  • Stress the importance of monitoring system resources.
    - Describe the script that continuously monitors CPU and memory usage.
    - Walk through the code example for system resource monitoring.
import psutil
import time

while True:
cpu_percent = psutil.cpu_percent()
memory_percent = psutil.virtual_memory().percent

print(f'CPU Usage: {cpu_percent}% | Memory Usage: {memory_percent}%')

time.sleep(10) # Monitor every 10 seconds

8. Automated Testing

  • Discuss the significance of automated testing in software development.
    - Introduce the concept of writing test functions using libraries like `unittest`.
    - Provide an example of writing and running automated tests.
import unittest

def add(a, b):
return a + b

class TestAddFunction(unittest.TestCase):
def test_add_positive_numbers(self):
result = add(3, 5)
self.assertEqual(result, 8)

def test_add_negative_numbers(self):
result = add(-3, -5)
self.assertEqual(result, -8)

if __name__ == '__main__':
unittest.main()

9. Auto-Generated Reports

  • Explain how automated report generation saves time and ensures consistency.
    - Present a script that generates reports from data using `pandas`.
    - Provide the code snippet and explain the report generation process.
import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 22]}

df = pd.DataFrame(data)
report_filename = '/path/to/report/report.xlsx'

df.to_excel(report_filename, index=False)

10. Task Scheduler

  • Emphasize the importance of scheduling recurring tasks.
    - Introduce the concept of task scheduling using the `schedule` library.
    - Present the code example for scheduling and running tasks.
import schedule
import time

def task_to_run():
print("Running the scheduled task")

schedule.every().day.at("08:00").do(task_to_run)

while True:
schedule.run_pending()
time.sleep(1)

Conclusion

- Summarize the 10 Python automation script ideas covered in the blog post.
- Emphasize the practicality and versatility of Python for automating various tasks.
- Encourage readers to explore these scripts, modify them to their needs, and continue learning.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Amit Bhargav
Amit Bhargav

Written by Amit Bhargav

Software developer passionate about Data Structures, Algorithms, and Optimization. Skilled in Java, C++, Python, AI, and Machine Learning.

No responses yet

Write a response

Recommended from Medium

Lists

See more recommendations