5 Essential Python Automation Scripts You Need to Try
Python is a powerful and versatile programming language that’s perfect for automating a variety of tasks. Whether for a beginner or an experienced developer, automation scripts can save time and reduce repetitive work. In this article, we’ll explore five essential Python automation scripts that can help streamline your workflow and boost productivity.
1. Automating File Organization
Manually organizing files can be tedious and time-consuming. With a simple Python script, we can automate this process to keep our directories neat and organized.
Script:
import os
import shutil
def organize_files(folder_path):
for filename in os.listdir(folder_path):
file_extension = filename.split('.')[-1]
destination_folder = os.path.join(folder_path, file_extension)
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
shutil.move(os.path.join(folder_path, filename), os.path.join(destination_folder, filename))
folder_path = '/path/to/your/folder'
organize_files(folder_path)
Explanation:
- This script sorts files into folders based on their extensions, creating new folders as needed.
2. Web Scraping with BeautifulSoup
Gathering data from websites can be automated using web scraping. BeautifulSoup is a popular library that easily extracts information from HTML and XML files.
Script:
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
titles = soup.find_all('h2')
for title in titles:
print(title.get_text())
url = 'https://example.com'
scrape_website(url)
Explanation:
- The script fetches the content of a webpage and prints all the text within
<h2>
tags.
3. Sending Automated Emails
There are some times when we want to automate the sending of emails. That’s because it can save time, especially for routine and daily communications. The smtplib library allows us to send emails using Python.
Script:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(to_email, subject, message):
from_email = 'your_email@example.com'
password = 'your_password'
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, password)
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
to_email = 'recipient@example.com'
subject = 'Test Email'
message = 'This is an automated email.'
send_email(to_email, subject, message)
Explanation:
- This script sends an email with a subject and message to a specified recipient.
4. Data Analysis with Pandas
Automating data analysis can help us quickly gain insights from large datasets. The Pandas library is a powerful tool for data manipulation and analysis. A short snippet of the usage of Pandas library in this case is given below:
Script:
import pandas as pd
def analyze_data(file_path):
df = pd.read_csv(file_path)
summary = df.describe()
print(summary)
file_path = '/path/to/your/data.csv'
analyze_data(file_path)
Explanation:
- It reads a CSV file and prints a summary of the dataset, including statistics like mean, standard deviation, and more.
5. Automating Backups
Regularly backing up important files is very important and always considered a best practice to recover crucial data in times of failures or crashes of the system. A Python script can automate the process of creating backups.
Script:
import os
import shutil
from datetime import datetime
def backup_files(source_folder, backup_folder):
current_time = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_subfolder = os.path.join(backup_folder, current_time)
shutil.copytree(source_folder, backup_subfolder)
print(f'Backup created at {backup_subfolder}')
source_folder = '/path/to/your/source_folder'
backup_folder = '/path/to/your/backup_folder'
backup_files(source_folder, backup_folder)
Explanation:
- This script creates a timestamped backup of a specified folder, ensuring that the important files are safely stored.
Conclusion
Python automation scripts can greatly enhance productivity by handling repetitive tasks efficiently. Whether it’s organizing files, scraping data from websites, sending emails, analyzing data, or creating backups, these scripts are simple to implement and can save valuable time.
Though some of the tasks can easily be automated with Bash too but that’s not a debate here and Python sometimes comes as a very handy and universal tool. In my opinion, it is easier to write code in Python especially when it comes to automating stuff, It always comes on top of my priority list.
Don’t forget to like, share, and save this for reference later! Spread the knowledge.
🔔 Follow Muhammad Usama Khan here and on LinkedIn for more insightful content on Cloud, DevOps, AI/Data, SRE and Cloud Native.