DEV Community

Devshi Bambhaniya
Devshi Bambhaniya

Posted on

11 Mindblowing Python Automation Scripts I Use Everyday in 2024

Python is a powerful and versatile programming language, making it an excellent choice for automation. Python can automate almost anything you can imagine, from simplifying repetitive tasks to handling complex processes. Here are 11 mindblowing Python automation scripts that I use every day to enhance productivity and streamline workflows.

1. Email Automation

Script Overview


This script automates the process of sending emails, making it incredibly useful for sending newsletters, updates, or notifications.

Key Features

  • Automates sending emails with attachments.
  • Supports multiple recipients.
  • Customizable subject and body content.

Example Script

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email(recipient, subject, body):
    sender_email = "youremail@example.com"
    sender_password = "yourpassword"

    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = recipient
    message['Subject'] = subject

    message.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
    text = message.as_string()
    server.sendmail(sender_email, recipient, text)
    server.quit()

send_email("recipient@example.com", "Subject Here", "Email body content here.")

Enter fullscreen mode Exit fullscreen mode

2. Web Scraping

Script Overview

Automate the process of extracting data from websites using web scraping with BeautifulSoup and Requests.

Key Features

  • Extracts data from HTML pages.
  • Parses and processes web data.
  • Saves extracted data to a file or database.

Example Script

import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    titles = soup.find_all('h1')

    for title in titles:
        print(title.get_text())

scrape_website("https://example.com")

Enter fullscreen mode Exit fullscreen mode

3. File Management


Script Overview


Automate the organization and management of files on your computer, such as sorting files into folders based on file types.

Key Features

  • Moves files to specified directories.
  • Renames files based on specific patterns.
  • Deletes unwanted files.

Example Script

import os
import shutil

def organize_files(directory):
    for filename in os.listdir(directory):
        if filename.endswith('.txt'):
            shutil.move(os.path.join(directory, filename), os.path.join(directory, 'TextFiles', filename))
        elif filename.endswith('.jpg'):
            shutil.move(os.path.join(directory, filename), os.path.join(directory, 'Images', filename))

organize_files('/path/to/your/directory')

Enter fullscreen mode Exit fullscreen mode

4. Data Analysis


Script Overview


Automate data analysis tasks using Pandas, a powerful data manipulation and analysis library.

Key Features

  • Reads and processes data from CSV files.
  • Performs data cleaning and transformation.
  • Generates summary statistics and visualizations.

Example Script

import pandas as pd

def analyze_data(file_path):
    data = pd.read_csv(file_path)
    summary = data.describe()
    print(summary)

analyze_data('data.csv')

Enter fullscreen mode Exit fullscreen mode

5. Automated Reports


Script Overview


Generate automated reports by extracting data from various sources and compiling it into a formatted document.

Key Features

  • Extracts data from databases or APIs.
  • Compiles data into a report format.
  • Sends the report via email or saves it locally.

Example Script

import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def generate_report(data):
    report = data.describe().to_string()
    return report

def send_report(report, recipient):
    sender_email = "youremail@example.com"
    sender_password = "yourpassword"

    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = recipient
    message['Subject'] = "Automated Report"

    message.attach(MIMEText(report, 'plain'))

    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
    text = message.as_string()
    server.sendmail(sender_email, recipient, text)
    server.quit()

data = pd.read_csv('data.csv')
report = generate_report(data)
send_report(report, "recipient@example.com")

Enter fullscreen mode Exit fullscreen mode

6. Social Media Automation


Script Overview


Automate posting content to social media platforms using APIs, such as Twitter or Facebook.

Key Features

  • Schedules and posts content.
  • Retrieves and analyzes social media metrics.
  • Automates interactions with followers.

Example Script

import tweepy

def post_tweet(message):
    api_key = "your_api_key"
    api_secret = "your_api_secret"
    access_token = "your_access_token"
    access_token_secret = "your_access_token_secret"

    auth = tweepy.OAuthHandler(api_key, api_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    api.update_status(message)

post_tweet("Hello, world! This is an automated tweet.")

Enter fullscreen mode Exit fullscreen mode

7. Database Backup


Script Overview


Automate the process of backing up databases to ensure data safety and integrity.

Key Features

  • Connects to the database.
  • Creates a backup file.
  • Stores the backup in a specified location.

Example Script

import os
import datetime
import sqlite3

def backup_database(db_path, backup_dir):
    connection = sqlite3.connect(db_path)
    backup_path = os.path.join(backup_dir, f"backup_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.db")
    with open(backup_path, 'wb') as f:
        for line in connection.iterdump():
            f.write(f'{line}\n'.encode('utf-8'))
    connection.close()

backup_database('example.db', '/path/to/backup/directory')

Enter fullscreen mode Exit fullscreen mode

8. Automated Testing


Script Overview


Automate software application testing for web applications using frameworks like Selenium.

Key Features

  • Automates browser interactions.
  • Runs test cases and reports results.
  • Integrates with CI/CD pipelines.

Example Script

from selenium import webdriver

def run_tests():
    driver = webdriver.Chrome()
    driver.get('https://example.com')
    assert "Example Domain" in driver.title
    driver.quit()

run_tests()

Enter fullscreen mode Exit fullscreen mode

9. Task Scheduling


Script Overview


Automate the scheduling of tasks using task schedulers like Schedule in Python.

Key Features

  • Schedules tasks to run at specific times.
  • Executes tasks at regular intervals.
  • Integrates with other automation scripts.
Example Script ``` import schedule import time def job(): print("Executing scheduled task...") schedule.every().day.at("10:00").do(job) while True: schedule.run_pending() time.sleep(1) ```

10. Web Form Filling

Script Overview

Automate the process of filling out web forms, saving time and reducing the risk of errors.

Key Features

  • Automates form input and submission.
  • Handles different types of form fields.
  • Captures and processes form responses.

Example Script

from selenium import webdriver

def fill_form():
    driver = webdriver.Chrome()
    driver.get('https://example.com/form')
    driver.find_element_by_name('name').send_keys('John Doe')
    driver.find_element_by_name('email').send_keys('johndoe@example.com')
    driver.find_element_by_name('submit').click()
    driver.quit()

fill_form()

Enter fullscreen mode Exit fullscreen mode

11. File Backup and Sync


Script Overview


Automate the backup and synchronization of files between different directories or cloud storage.

Key Features

  • Copies files to backup locations.
  • Syncs files across multiple devices.
  • Schedules regular backups.

Example Script

import shutil
import os

def backup_files(source_dir, backup_dir):
    for filename in os.listdir(source_dir):
        source_file = os.path.join(source_dir, filename)
        backup_file = os.path.join(backup_dir, filename)
        shutil.copy2(source_file, backup_file)

backup_files('/path/to/source/directory', '/path/to/backup/directory')

Enter fullscreen mode Exit fullscreen mode

Conclusion


Python development automation can significantly improve productivity by handling repetitive tasks, optimizing workflows, and ensuring accuracy. Whether managing emails, scraping data, organizing files, or backing up databases, these 11 Python automation scripts can make your daily tasks more efficient and less time-consuming. Integrating these scripts into your routine gives you more time to focus on what truly matters – growing your business and enhancing your skills.

Top comments (2)

Collapse
 
sreno77 profile image
Scott Reno

These are very useful examples. Thanks for sharing!

Collapse
 
devshi profile image
Devshi Bambhaniya

Thanks, @sreno77. Read my article.