Home > Backend Development > Python Tutorial > Python Scripts to Automate Your Daily Tasks

Python Scripts to Automate Your Daily Tasks

Mary-Kate Olsen
Release: 2024-11-29 14:02:11
Original
632 people have browsed it

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.")

Copy after login
Copy after login

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")

Copy after login
Copy after login

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))

Copy after login
Copy after login

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")

Copy after login

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!")

Copy after login

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"))

Copy after login

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)

Copy after login

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.

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.")

Copy after login
Copy after login

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 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")

Copy after login
Copy after login

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 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))

Copy after login
Copy after login

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!

The above is the detailed content of Python Scripts to Automate Your Daily Tasks. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template