DEV Community

Trix Cyrus
Trix Cyrus

Posted on

How to Automate Everyday Tasks with Python

Author: Trix Cyrus

Waymap Pentesting tool: Click Here
TrixSec Github: Click Here

Python is a versatile and easy-to-learn programming language, and one of its greatest strengths is the ability to automate repetitive tasks. Whether it’s organizing files, scraping web data, sending emails, or managing system resources, Python has libraries and modules that can help make everyday tasks more efficient.

In this guide, we’ll explore different ways you can automate tasks with Python and provide examples to help you get started.

1. Automating File and Folder Management

Python’s built-in os and shutil modules allow you to interact with your computer’s file system. You can use these modules to automate file creation, deletion, and organization tasks.

import os
import shutil

# Folder paths
source_folder = '/path/to/source'
destination_folders = {
    'Images': '/path/to/images',
    'Documents': '/path/to/docs',
    'Music': '/path/to/music'
}

# File extensions
file_types = {
    '.jpg': 'Images',
    '.png': 'Images',
    '.pdf': 'Documents',
    '.mp3': 'Music'
}

# Move files to respective folders
for filename in os.listdir(source_folder):
    ext = os.path.splitext(filename)[1].lower()
    if ext in file_types:
        shutil.move(os.path.join(source_folder, filename), destination_folders[file_types[ext]])
Enter fullscreen mode Exit fullscreen mode

This script scans the source folder, identifies file types based on extensions, and moves them to their respective folders.

2. Automating Web Scraping
Web scraping allows you to collect data from websites automatically. The requests and BeautifulSoup libraries are commonly used to send HTTP requests and parse HTML content.

import requests
from bs4 import BeautifulSoup

# URL of the website to scrape
url = 'https://news.ycombinator.com/'

# Send a GET request
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Extract headlines
headlines = soup.find_all('a', class_='storylink')

# Print each headline
for headline in headlines:
    print(headline.text)
Enter fullscreen mode Exit fullscreen mode

This script scrapes and prints all the headlines from the front page of Hacker News.

3. Automating Email Sending

You can send emails automatically with Python using the smtplib module. This can be useful for sending reminders, reports, or notifications.

import smtplib
from email.mime.text import MIMEText

# Email configuration
sender_email = 'youremail@gmail.com'
receiver_email = 'recipient@gmail.com'
subject = 'Daily Reminder'
body = 'Don’t forget to complete your task today!'

# Create the email message
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email

# Send the email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.starttls()
    server.login(sender_email, 'yourpassword')
    server.sendmail(sender_email, receiver_email, msg.as_string())
Enter fullscreen mode Exit fullscreen mode

This script sends a simple reminder email using Gmail’s SMTP server.

4. Automating Data Entry in Google Sheets

With the gspread library and Google Sheets API, you can automate the process of writing data into spreadsheets.

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# Google Sheets API setup
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
client = gspread.authorize(creds)

# Open the sheet
sheet = client.open('MySheet').sheet1

# Write data to the sheet
sheet.update_cell(1, 1, 'Task')
sheet.update_cell(1, 2, 'Status')
sheet.update_cell(2, 1, 'Complete Python Script')
sheet.update_cell(2, 2, 'Done')
Enter fullscreen mode Exit fullscreen mode

This script logs into Google Sheets and writes data to a specified sheet.

5. Automating System Monitoring

You can use Python to monitor system resources such as CPU, memory, and disk usage. This is useful for server management and diagnostics.

import psutil

# Get CPU and memory usage
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()

print(f"CPU Usage: {cpu_usage}%")
print(f"Memory Usage: {memory_info.percent}%")
Enter fullscreen mode Exit fullscreen mode

This script prints the current CPU and memory usage of your machine.

6. Automating Browser Tasks

Python’s selenium library allows you to control a web browser through scripts. This is useful for tasks like filling out forms, navigating websites, and scraping dynamic content.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Set up the browser
driver = webdriver.Chrome()

# Open Google
driver.get('https://www.google.com')

# Search for a query
search_box = driver.find_element_by_name('q')
search_box.send_keys('Python automation')
search_box.send_keys(Keys.RETURN)
Enter fullscreen mode Exit fullscreen mode

This script opens Google, searches for "Python automation," and shows the search results.

~TrixSec

Top comments (0)