fbpx

HomeBlogEnglish Posts14 Python Automation Scripts to Simplify Your Daily Tasks

14 Python Automation Scripts to Simplify Your Daily Tasks

In today’s fast-paced world, automation has become a key tool in streamlining daily tasks and increasing productivity.

Python, being one of the most versatile and easy-to-learn programming languages, offers numerous libraries and frameworks that can help you automate a wide variety of tasks—from sending emails and managing files to web scraping and data analysis.

In this blog post, we’ll walk you through 14 Python automation scripts that can simplify your daily routine, saving you time and effort.

Sure! Below are 14 Python automation scripts, each designed to simplify a specific daily task. Each script is explained and provided separately.

1. Automating Email Sending

This script sends an email using Python’s smtplib library.

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

def send_email(subject, body, to_email):
    from_email = "your_email@example.com"
    password = "your_email_password"

    # Set up the MIME
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # Add the body to the email
    msg.attach(MIMEText(body, 'plain'))

    # Set up the server
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email, password)

    # Send the email
    text = msg.as_string()
    server.sendmail(from_email, to_email, text)
    server.quit()

# Example usage
send_email("Subject", "This is the body of the email", "recipient@example.com")

2. Renaming Multiple Files in a Directory

This script renames all files in a specified directory by adding a prefix to the filenames.

import os

def rename_files(directory, prefix):
    for filename in os.listdir(directory):
        new_name = prefix + filename
        os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

# Example usage
rename_files("/path/to/your/folder", "prefix_")

3. Web Scraping with BeautifulSoup

This script extracts data from a website using BeautifulSoup.

import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    # Example: Extracting all headlines from a news site
    headlines = soup.find_all('h2')
    for headline in headlines:
        print(headline.text)

# Example usage
scrape_website("https://example.com/news")

4. Automating File Backup

This script creates a backup of a specified directory.

import shutil
import os
from datetime import datetime

def backup_folder(source_folder, backup_folder):
    current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_name = f"{backup_folder}/backup_{current_time}"
    shutil.copytree(source_folder, backup_name)
    print(f"Backup created at {backup_name}")

# Example usage
backup_folder("/path/to/your/folder", "/path/to/backup/location")

5. Automatically Downloading Files from URLs

This script downloads files from a list of URLs.

import requests

def download_files(url_list, save_folder):
    for url in url_list:
        file_name = url.split("/")[-1]
        response = requests.get(url)
        with open(f"{save_folder}/{file_name}", 'wb') as file:
            file.write(response.content)
        print(f"Downloaded {file_name}")

# Example usage
urls = ["https://example.com/file1.jpg", "https://example.com/file2.jpg"]
download_files(urls, "/path/to/save/folder")

6. Reading and Writing to CSV Files

This script reads data from a CSV file, processes it, and writes the results to a new CSV file.

import csv

def process_csv(input_file, output_file):
    with open(input_file, mode='r') as infile, open(output_file, mode='w') as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)

        for row in reader:
            # Example: Convert all text to uppercase
            writer.writerow([cell.upper() for cell in row])

# Example usage
process_csv("input.csv", "output.csv")

7. Automating Social Media Posting

This script posts a message to Twitter using the tweepy library.

import tweepy

def post_tweet(message):
    consumer_key = "your_consumer_key"
    consumer_secret = "your_consumer_secret"
    access_token = "your_access_token"
    access_token_secret = "your_access_token_secret"

    # Authenticate to Twitter
    auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
    api = tweepy.API(auth)

    # Post the tweet
    api.update_status(message)
    print(f"Posted tweet: {message}")

# Example usage
post_tweet("Hello, Twitter!")

8. Automating System Health Check

This script checks system memory and CPU usage and logs it.

import psutil
import datetime

def check_system_health(log_file):
    cpu_usage = psutil.cpu_percent(interval=1)
    memory_info = psutil.virtual_memory()

    with open(log_file, 'a') as f:
        f.write(f"{datetime.datetime.now()} - CPU: {cpu_usage}%, Memory: {memory_info.percent}%\n")

# Example usage
check_system_health("system_health_log.txt")

9. Automating PDF Generation

This script generates a PDF from a text file using the fpdf library.

from fpdf import FPDF

def generate_pdf(input_text_file, output_pdf_file):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)

    with open(input_text_file, 'r') as file:
        for line in file:
            pdf.cell(200, 10, txt=line, ln=True)

    pdf.output(output_pdf_file)

# Example usage
generate_pdf("input.txt", "output.pdf")

10. Automating Data Analysis with Pandas

This script reads data from a CSV file, analyzes it, and outputs the results.

import pandas as pd

def analyze_data(input_csv):
    df = pd.read_csv(input_csv)
    summary = df.describe()
    print(summary)

# Example usage
analyze_data("data.csv")

11. Sending Automated Birthday Emails

This script checks a list of birthdays and sends an automated email.

import smtplib
from email.mime.text import MIMEText
import pandas as pd
from datetime import datetime

def send_birthday_emails(birthday_file):
    today = datetime.today().strftime('%m-%d')
    df = pd.read_csv(birthday_file)

    for index, row in df.iterrows():
        if today == row['Birthday']:
            send_email(f"Happy Birthday, {row['Name']}!", "Wishing you a fantastic day!", row['Email'])

# Define send_email function (reuse from the first script) and call it here.

# Example usage
send_birthday_emails("birthdays.csv")

12. Automating Database Backup

This script creates a backup of a MySQL database.

import os

def backup_database(db_name, user, password, backup_folder):
    current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_file = f"{backup_folder}/{db_name}_backup_{current_time}.sql"
    os.system(f"mysqldump -u {user} -p{password} {db_name} > {backup_file}")
    print(f"Backup created at {backup_file}")

# Example usage
backup_database("mydatabase", "dbuser", "dbpassword", "/path/to/backup/folder")

13. Web Scraping for Price Monitoring

This script scrapes a product’s price from an e-commerce site and alerts if it drops.

import requests
from bs4 import BeautifulSoup

def check_price(url, target_price):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    price = float(soup.find("span", {"id": "price"}).text.strip("$"))

    if price < target_price:
        print(f"Price drop alert! The price is now ${price}")

# Example usage
check_price("https://example.com/product", 100.00)

14. Automating Directory Cleanup

This script deletes files older than a specified number of days from a directory.

import os
import time

def cleanup_directory(directory, days_old):
    now = time.time()
    cutoff = now - (days_old * 86400)

    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            if os.stat(file_path).st_mtime < cutoff:
                os.remove(file_path)
                print(f"Deleted {filename}")

# Example usage
cleanup_directory("/path/to/your/folder", 30)

These scripts can be adapted and extended according to your specific needs, helping you automate various tasks and improve your productivity.

Automation with Python can dramatically transform the way you handle repetitive tasks, freeing up more time for creative and strategic activities. Whether you’re looking to automate email sending, manage your files, or even analyze data, Python provides the tools you need to get the job done efficiently.

If you’re new to Python, there are plenty of resources available to help you get started.

For more information, check out the Python documentation, explore Automate the Boring Stuff with Python, or dive into Real Python’s tutorials.

By incorporating these scripts into your daily workflow, you can not only boost your productivity but also develop a deeper understanding of Python and its powerful capabilities. Happy automating!

You May Also Like Reading :

2 thoughts on “14 Python Automation Scripts to Simplify Your Daily Tasks

  1. Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol

  2. Program iz You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

Leave a Reply

Your email address will not be published. Required fields are marked *

This is a staging environment

Thank you for your upload