10 Python Scripts to Automate Your Daily Tasks

codepicker

CodePicker

Posted on November 22, 2024

10 Python Scripts to Automate Your Daily Tasks

A must-have collection for everyone...

Python has transformed the way we approach automation, thanks to its simplicity and powerful libraries. Whether you're a tech enthusiast, a busy professional, or just looking to simplify your day-to-day routines, Python can help automate repetitive tasks, save time, and increase efficiency. Here’s a collection of 10 essential Python scripts that can help you automate various aspects of your daily life.

Let’s dive in!


1.Automate Email Sending

Manually sending emails, especially recurring ones, can be time-consuming. With Python’s smtplib library, you can automate this process effortlessly. Whether it’s sending reminders, updates, or personalized messages, this script can handle it all.

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

def send_email(receiver_email, subject, body):
    sender_email = "your_email@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
            print("Email sent successfully!")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
send_email("receiver_email@example.com", "Subject Here", "Email body goes here.")

Enter fullscreen mode Exit fullscreen mode

This script can be easily integrated into a larger workflow, like sending reports or alerts.

2.File Organizer

If your Downloads folder is a chaotic mess, this script is for you. It organizes files by their extensions, neatly placing them into subfolders. No more sifting through dozens of files to find what you need!

import os
from shutil import move

def organize_folder(folder_path):
    for file in os.listdir(folder_path):
        if os.path.isfile(os.path.join(folder_path, file)):
            ext = file.split('.')[-1]
            ext_folder = os.path.join(folder_path, ext)
            os.makedirs(ext_folder, exist_ok=True)
            move(os.path.join(folder_path, file), os.path.join(ext_folder, file))

# Example usage
organize_folder("C:/Users/YourName/Downloads")

Enter fullscreen mode Exit fullscreen mode

This script is especially useful for managing files like PDFs, images, or documents.

3.Web Scraping News Headlines

Stay updated with the latest news by scraping headlines from your favorite website. Python’s 'requests' and 'BeautifulSoup' libraries make this process seamless.

import requests
from bs4 import BeautifulSoup

def fetch_headlines(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    headlines = [h.text for h in soup.find_all('h2', class_='headline')]
    return headlines

# Example usage
headlines = fetch_headlines("https://news.ycombinator.com/")
print("\n".join(headlines))

Enter fullscreen mode Exit fullscreen mode

Whether you’re a news junkie or need updates for work, this script can be scheduled to run daily.

4.Daily Weather Notification

Start your day with a weather update! This script fetches weather data for your city using the OpenWeatherMap API and displays the temperature and forecast.

import requests

def get_weather(city):
    api_key = "your_api_key"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url).json()
    if response.get("main"):
        temp = response['main']['temp']
        weather = response['weather'][0]['description']
        print(f"The current weather in {city} is {temp}°C with {weather}.")
    else:
        print("City not found!")

# Example usage
get_weather("New York")

Enter fullscreen mode Exit fullscreen mode

With minor tweaks, you can have it send notifications directly to your phone.

5.Automate Social Media Posts

Scheduling social media posts is a breeze with Python. Use the 'tweepy' library to post tweets programmatically.

import tweepy

def post_tweet(api_key, api_key_secret, access_token, access_token_secret, tweet):
    auth = tweepy.OAuthHandler(api_key, api_key_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    api.update_status(tweet)
    print("Tweet posted!")

# Example usage
post_tweet("api_key", "api_key_secret", "access_token", "access_token_secret", "Hello, Twitter!")

Enter fullscreen mode Exit fullscreen mode

Ideal for social media managers and content creators who want to plan posts in advance.

6.PDF to Text Conversion

Extracting text from PDFs manually is tedious. This script simplifies the process using the 'PyPDF2' library.

from PyPDF2 import PdfReader

def pdf_to_text(file_path):
    reader = PdfReader(file_path)
    text = ""
    for page in reader.pages:
        text += page.extract_text()
    return text

# Example usage
print(pdf_to_text("sample.pdf"))

Enter fullscreen mode Exit fullscreen mode

Great for archiving or analyzing text-heavy documents.

7.Expense Tracker with CSV

Keep track of your expenses by logging them into a CSV file. This script helps you maintain a digital record that you can analyze later.

import csv

def log_expense(file_name, date, item, amount):
    with open(file_name, mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([date, item, amount])
        print("Expense logged!")

# Example usage
log_expense("expenses.csv", "2024-11-22", "Coffee", 4.5)

Enter fullscreen mode Exit fullscreen mode

Turn this into a habit, and you’ll have a clear picture of your spending patterns.

8.Automate Desktop Notifications

Need reminders or alerts on your computer? This script uses the 'plyer' library to send desktop notifications.

from plyer import notification

def send_notification(title, message):
    notification.notify(
        title=title,
        message=message,
        app_name="Task Automation"
    )

# Example usage
send_notification("Reminder", "Meeting at 3 PM.")

Enter fullscreen mode Exit fullscreen mode

Perfect for task management and event reminders.

9.Website Availability Checker

Monitor the uptime of your website or favorite platforms with this simple script.

import requests

def check_website(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print(f"{url} is online!")
        else:
            print(f"{url} is down! Status code: {response.status_code}")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
check_website("https://www.google.com")

Enter fullscreen mode Exit fullscreen mode

Useful for web developers and business owners.

10.Automate Data Backup

Never worry about losing important files again. This script automates file backups to a designated location.

import shutil

def backup_files(source_folder, backup_folder):
    shutil.copytree(source_folder, backup_folder, dirs_exist_ok=True)
    print("Backup completed!")

# Example usage
backup_files("C:/ImportantData", "D:/Backup")

Enter fullscreen mode Exit fullscreen mode

Run it weekly or daily to ensure your data is always safe.


These 10 scripts demonstrate how Python can tackle repetitive tasks and simplify your daily routine. From managing files to posting on social media, automation opens endless possibilities. Pick a script, customize it, and integrate it into your workflow. Soon, you’ll wonder how you ever lived without Python automation!

Which one will you try first?

Let us know in comments section!

💖 💪 🙅 🚩
codepicker
CodePicker

Posted on November 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related