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

Python Scripts to Automate Your Daily Tasks

Nov 29, 2024 pm 02:02 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles