Top 10 Python Automation Scripts That You Should Try Once
Top 10 Python Automation Scripts That You Should Try Once
by Saptorshee Nag
0 of 34 secondsVolume 0%
Automation in Python
Python automation means using the language to write
scripts, programs, or other tools that carry out automatic
processes without the need for human
interaction. Automation can be used for several processes including
file management, web scraping, data analysis, system monitoring,
and more.
Here are the common automation tasks used in Python:
File Management:
Reading/Writing Files: Automate tasks such as reading
data.
Automated Reporting: Collect data from various
sources and generate reports.
Testing:
Unit Testing: Automate the testing of code to ensure it
works as expected.
Integration Testing: Test interactions between
different parts of a system.
Thus, automation is a crucial aspect of programming with Python
nowadays and has many applications and use cases across diverse
fields.
Python
1
import os
2
import shutil
3
4
def organize_files_by_extension(directory):
5
"""
6
Organizes files in the given directory by their extensions.
7
8
:param directory: Path to the directory to organize.
9
"""
10
# Iterate through all files in the directory
11
for filename in [Link](directory):
12
# Ignore directories
13
if [Link]([Link](directory, filename)):
14
continue
15
16
# Extract file extension
17
ext = [Link]('.')[-1]
18
ext_dir = [Link](directory, ext)
19
20
# Create a directory for the extension if it doesn't exist
21
[Link](ext_dir, exist_ok=True)
22
23
# Construct full file paths
24
src_path = [Link](directory, filename)
25
dest_path = [Link](ext_dir, filename)
26
27
# Move file to the new directory
28
[Link](src_path, dest_path)
29
print(f'Moved {filename} to {ext_dir}')
30
31
# Example usage
32
organize_files_by_extension('/path/to/your/directory')
Python
1
import requests
2
from bs4 import BeautifulSoup
3
4
def extract_article_titles(url):
5
"""
6
Extracts article titles from a web page.
7
8
:param url: URL of the web page to scrape.
9
:return: List of article titles.
10
"""
11
try:
12
# Fetch the content of the URL
13
response = [Link](url)
14
response.raise_for_status() # Raise an HTTPError if the HTTP request returned an
unsuccessful status code
15
except [Link] as e:
16
print(f"Error fetching the URL: {e}")
17
return []
18
19
# Parse the HTML content
20
soup = BeautifulSoup([Link], '[Link]')
21
22
# Extract article titles
23
titles = []
24
for header in soup.find_all(['h1', 'h2', 'h3']): # Adjust tags as needed
25
title = header.get_text(strip=True)
26
if title: # Only add non-empty titles
27
[Link](title)
28
29
return titles
30
31
# Example usage
32
url = '[Link]
33
titles = extract_article_titles(url)
34
for i, title in enumerate(titles, start=1):
35
print(f'{i}. {title}')
Python
1
import shutil
2
import os
3
import platform
4
5
def check_disk_usage(threshold):
6
"""
7
Checks the disk usage and alerts if free space is below the given threshold.
8
9
:param threshold: The minimum free space percentage allowed before an alert is
raised.
10
"""
11
# Get disk usage statistics
12
total, used, free = shutil.disk_usage('/')
13
14
# Calculate percentage of free space
15
free_percent = free / total * 100
16
17
# Print the disk usage details
18
print(f"Total: {total / (1024**3):.2f} GB")
19
print(f"Used: {used / (1024**3):.2f} GB")
20
print(f"Free: {free / (1024**3):.2f} GB ({free_percent:.2f}%)")
21
22
# Check if free space is below the threshold
23
if free_percent < threshold:
24
print(f"Warning: Only {free_percent:.2f}% free space left!")
25
else:
26
print(f"Sufficient disk space available ({free_percent:.2f}% free).")
27
28
# Example usage
29
threshold = 20 # Set threshold for free space percentage
30
check_disk_usage(threshold)
Python
1
import requests
2
3
def fetch_weather(api_key, city):
4
"""
5
Fetches and prints weather data for a given city using OpenWeatherMap API.
6
7
:param api_key: Your OpenWeatherMap API key.
8
:param city: City name to fetch the weather for.
9
"""
10
# API endpoint
11
url = '[Link]
12
13
# Parameters to be sent with the request
14
params = {
15
'q': city,
16
'appid': api_key,
17
'units': 'metric' # Use 'imperial' for Fahrenheit
18
}
19
20
try:
21
# Send GET request
22
response = [Link](url, params=params)
23
response.raise_for_status() # Raise an HTTPError for bad responses
24
25
# Parse JSON response
26
data = [Link]()
27
28
# Extract weather information
29
city_name = data['name']
30
weather = data['weather'][0]['description']
31
temp = data['main']['temp']
32
feels_like = data['main']['feels_like']
33
humidity = data['main']['humidity']
34
wind_speed = data['wind']['speed']
35
36
# Print weather information
37
print(f"Weather in {city_name}:")
38
print(f" Description: {weather}")
39
print(f" Temperature: {temp}°C")
40
print(f" Feels Like: {feels_like}°C")
41
print(f" Humidity: {humidity}%")
42
print(f" Wind Speed: {wind_speed} m/s")
43
44
except [Link] as e:
45
print(f"Error fetching weather data: {e}")
46
except KeyError as e:
47
print(f"Error parsing weather data: {e}")
48
49
# Example usage
50
api_key = 'your_api_key_here' # Replace with your OpenWeatherMap API key
51
city = 'London'
52
fetch_weather(api_key, city)
Python
1
import pandas as pd
2
3
def clean_csv(input_file, output_file):
4
"""
5
Cleans a CSV file by removing missing values, converting data types, renaming
columns,
6
and filtering rows.
7
8
:param input_file: Path to the input CSV file.
9
:param output_file: Path to the output cleaned CSV file.
10
"""
11
# Load CSV data into DataFrame
12
df = pd.read_csv(input_file)
13
14
# Print original data summary
15
print("Original Data Summary:")
16
print([Link]())
17
print([Link](), "\n")
18
19
# Remove rows with missing values
20
[Link](inplace=True)
21
22
# Convert data types (example: converting 'date' to datetime)
23
# Ensure to adjust the column names and types as per your CSV
24
if 'date' in [Link]:
25
df['date'] = pd.to_datetime(df['date'], errors='coerce')
26
27
# Rename columns (example: renaming 'old_name' to 'new_name')
28
# Ensure to adjust the column names as per your CSV
29
[Link](columns={'old_name': 'new_name'}, inplace=True)
30
31
# Filter rows (example: keep only rows where 'column' > value)
32
# Adjust the filter conditions as per your needs
33
if 'column' in [Link]:
34
df = df[df['column'] > value]
35
36
# Print cleaned data summary
37
print("Cleaned Data Summary:")
38
print([Link]())
39
print([Link](), "\n")
40
41
# Save cleaned data to new CSV file
42
df.to_csv(output_file, index=False)
43
print(f"Cleaned data saved to {output_file}")
44
45
# Example usage
46
input_file = '[Link]'
47
output_file = 'cleaned_data.csv'
48
clean_csv(input_file, output_file)
49
6. Battery Indicator
Creating a Python automation script for a battery indicator typically
involves reading the battery status and providing feedback through
an appropriate interface, such as a console output, GUI application, or
physical indicator (like an LED).
3
def read_battery_status(file_path):
4
"""
5
Reads the battery status from the specified file.
6
7
:param file_path: Path to the battery status file.
8
:return: Battery charge level as an integer percentage.
9
"""
10
try:
11
with open(file_path, 'r') as file:
12
capacity = [Link]().strip()
13
return int(capacity)
14
except (FileNotFoundError, ValueError) as e:
15
print(f"Error reading battery status: {e}")
16
return None
17
18
def print_battery_status(charge_level):
19
"""
20
Prints the battery status to the console.
21
22
:param charge_level: Current battery charge level as an integer percentage.
23
"""
24
if charge_level is not None:
25
print(f"Battery level: {charge_level}%")
26
27
# Example usage
28
BATTERY_FILE_PATH = '/sys/class/power_supply/BAT0/capacity' # Example path for
Linux
29
30
try:
31
while True:
32
charge_level = read_battery_status(BATTERY_FILE_PATH)
33
print_battery_status(charge_level)
34
[Link](60) # Check every 60 seconds
35
36
except KeyboardInterrupt:
37
print("Exiting...")
Python
1
import fitz # PyMuPDF
2
3
def pdf_to_images(pdf_file, output_folder):
4
"""
5
Converts each page of a PDF file to an image (PNG).
6
7
:param pdf_file: Path to the PDF file.
8
:param output_folder: Path to the output folder where images will be saved.
9
"""
10
# Open the PDF file
11
pdf_document = [Link](pdf_file)
12
13
# Iterate through each page of the PDF
14
for page_num in range(len(pdf_document)):
15
# Get the page
16
page = pdf_document.load_page(page_num)
17
18
# Convert page to image (PNG)
19
image = page.get_pixmap()
20
21
# Save image to output folder
22
image_path = f"{output_folder}/page_{page_num + 1}.png"
23
[Link](image_path)
24
print(f"Page {page_num + 1} saved as {image_path}")
25
26
# Close the PDF document
27
pdf_document.close()
28
29
# Example usage
30
if __name__ == "__main__":
31
pdf_file = "[Link]" # Replace with your PDF file path
32
output_folder = "output_images" # Replace with your desired output folder
33
34
# Create output folder if it doesn't exist
35
import os
36
if not [Link](output_folder):
37
[Link](output_folder)
38
39
# Convert PDF to images
40
pdf_to_images(pdf_file, output_folder)
python pdf_to_image.py
8. Email Scheduler
Creating an email scheduler using Python involves automating the
process of sending emails at scheduled intervals or specific times.
This can be accomplished by combining Python’s smtplib for sending
emails and schedule or datetime for scheduling tasks.
This script will allow you to communicate with your contacts easily
and say good-bye to sending emails by hand. Emails can be
automatically scheduled and sent at a specified time with this script.
Python
1
import smtplib
2
import schedule
3
import time
4
from [Link] import MIMEMultipart
5
from [Link] import MIMEText
6
from datetime import datetime
7
8
def send_email(subject, body, to_email):
9
"""
10
Sends an email with the specified subject and body.
11
12
:param subject: Subject of the email.
13
:param body: Body content of the email.
14
:param to_email: Recipient email address.
15
"""
16
from_email = "your_email@[Link]" # Replace with your email address
17
password = "your_password" # Replace with your email password
18
19
# Create the email content
20
message = MIMEMultipart()
21
message['From'] = from_email
22
message['To'] = to_email
23
message['Subject'] = subject
24
25
[Link](MIMEText(body, 'plain'))
26
27
try:
28
# Connect to the SMTP server
29
server = [Link]('[Link]', 587) # Replace with your SMTP server
and port
30
[Link]() # Secure the connection
31
[Link](from_email, password)
32
33
# Send the email
34
server.send_message(message)
35
print(f"Email sent to {to_email} at {[Link]()}")
36
37
# Disconnect from the server
38
[Link]()
39
except Exception as e:
40
print(f"Failed to send email: {e}")
41
42
def schedule_email():
43
"""
44
Schedules the email to be sent.
45
"""
46
subject = "Scheduled Email"
47
body = "This is an automatically scheduled email."
48
to_email = "recipient@[Link]" # Replace with recipient email address
49
50
send_email(subject, body, to_email)
51
52
# Schedule the email to be sent every day at a specific time
53
schedule_time = "14:00" # Replace with your desired schedule time (24-hour format)
54
[Link]().[Link](schedule_time).do(schedule_email)
55
56
print(f"Email scheduler started. Will send emails every day at {schedule_time}.")
57
58
try:
59
while True:
60
# Run pending scheduled tasks
61
schedule.run_pending()
62
[Link](1)
63
except KeyboardInterrupt:
64
print("Email scheduler stopped.")
9. Image Optimizer
This Python automation script lets you easily edit and modify your
images like an expert with only a few clicks, eliminating the need for
pricey programmes or sophisticated editing equipment.
Python
1
from PIL import Image
2
import os
3
4
def optimize_image(input_path, output_path, quality=85, max_width=None,
max_height=None):
5
"""
6
Optimize an image by resizing and adjusting its quality.
7
8
:param input_path: Path to the input image file.
9
:param output_path: Path to save the optimized image file.
10
:param quality: Image quality for the output (1 to 100).
11
:param max_width: Maximum width for resizing (optional).
12
:param max_height: Maximum height for resizing (optional).
13
"""
14
try:
15
# Open an image file
16
with [Link](input_path) as img:
17
print(f"Optimizing {input_path}...")
18
19
# Resize the image if max_width or max_height is specified
20
if max_width or max_height:
21
[Link]((max_width, max_height), [Link])
22
23
# Save the image with the specified quality
24
[Link](output_path, optimize=True, quality=quality)
25
print(f"Saved optimized image to {output_path}")
26
27
except Exception as e:
28
print(f"Error optimizing {input_path}: {e}")
29
30
def optimize_images_in_directory(directory, output_directory, quality=85,
max_width=None, max_height=None):
31
"""
32
Optimize all images in the specified directory.
33
34
:param directory: Directory containing images to optimize.
35
:param output_directory: Directory to save optimized images.
36
:param quality: Image quality for the output (1 to 100).
37
:param max_width: Maximum width for resizing (optional).
38
:param max_height: Maximum height for resizing (optional).
39
"""
40
# Create the output directory if it doesn't exist
41
if not [Link](output_directory):
42
[Link](output_directory)
43
44
# Iterate through all files in the directory
45
for filename in [Link](directory):
46
input_path = [Link](directory, filename)
47
output_path = [Link](output_directory, filename)
48
49
# Check if the file is an image
50
if [Link]().endswith(('png', 'jpg', 'jpeg', 'gif', 'bmp')):
51
optimize_image(input_path, output_path, quality, max_width, max_height)
52
53
# Example usage
54
if __name__ == "__main__":
55
input_dir = "input_images" # Replace with your input directory
56
output_dir = "optimized_images" # Replace with your output directory
57
image_quality = 85 # Adjust quality as needed (1 to 100)
58
max_img_width = 800 # Replace with max width or None
59
max_img_height = 600 # Replace with max height or None
60
61
optimize_images_in_directory(input_dir, output_dir, quality=image_quality,
max_width=max_img_width, max_height=max_img_height)
Python
1
import os
2
import subprocess
3
4
def optimize_video(input_path, output_path, resolution="1280x720", bitrate="1M"):
5
"""
6
Optimize a video file using ffmpeg.
7
8
:param input_path: Path to the input video file.
9
:param output_path: Path to save the optimized video file.
10
:param resolution: Resolution for the output video (e.g., '1280x720').
11
:param bitrate: Bitrate for the output video (e.g., '1M' for 1 Mbps).
12
"""
13
try:
14
print(f"Optimizing {input_path}...")
15
16
# Construct the ffmpeg command
17
command = [
18
'ffmpeg',
19
'-i', input_path,
20
'-vf', f'scale={resolution}',
21
'-b:v', bitrate,
22
'-c:a', 'copy',
23
output_path
24
]
25
26
# Run the command
27
[Link](command, check=True)
28
print(f"Saved optimized video to {output_path}")
29
30
except [Link] as e:
31
print(f"Error optimizing {input_path}: {e}")
32
33
def optimize_videos_in_directory(directory, output_directory, resolution="1280x720",
bitrate="1M"):
34
"""
35
Optimize all videos in the specified directory.
36
37
:param directory: Directory containing videos to optimize.
38
:param output_directory: Directory to save optimized videos.
39
:param resolution: Resolution for the output videos (e.g., '1280x720').
40
:param bitrate: Bitrate for the output videos (e.g., '1M' for 1 Mbps).
41
"""
42
# Create the output directory if it doesn't exist
43
if not [Link](output_directory):
44
[Link](output_directory)
45
46
# Iterate through all files in the directory
47
for filename in [Link](directory):
48
input_path = [Link](directory, filename)
49
output_path = [Link](output_directory, filename)
50
51
# Check if the file is a video
52
if [Link]().endswith(('mp4', 'mkv', 'mov', 'avi', 'flv', 'wmv', 'webm')):
53
optimize_video(input_path, output_path, resolution, bitrate)
54
55
# Example usage
56
if __name__ == "__main__":
57
input_dir = "input_videos" # Replace with your input directory
58
output_dir = "optimized_videos" # Replace with your output directory
59
video_resolution = "1280x720" # Replace with desired resolution (e.g., '1920x1080')
60
video_bitrate = "1M" # Replace with desired bitrate (e.g., '500K' for 500 kbps)
61
62
optimize_videos_in_directory(input_dir, output_dir, resolution=video_resolution,
bitrate=video_bitrate)
Conclusion
These Python Automation Scripts have been designed on a variety of
factors to give you the best automation experience across your daily
tasks and everyday projects.