17 Mindblowing Python Automation Scripts I Use Everyday
17 Mindblowing Python Automation Scripts I Use Everyday
Python is an incredibly versatile language that excels at automation. Whether it's automating mundane tasks, managing files, or fetching data, Python scripts can significantly boost productivity. Here, I share 17 Python automation scripts that I use daily.
Table of Contents
- Email Automation
- Web Scraping
- File Management
- Data Analysis
- Social Media Automation
- Reminder Notifications
- Data Backup
- Report Generation
- Image Processing
- Web Testing
- API Integration
- Database Management
- Finance Management
- Task Automation
- Weather Forecasting
- Personal Assistant
- Network Monitoring
1. Email Automation
Sending and receiving emails can be automated using Python. With libraries like smtplib
and imaplib
, you can send emails, read emails, and even sort your inbox.
Script Example:
pythonimport smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email):
from_email = "your_email@example.com"
from_password = "your_password"
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, from_password)
server.send_message(msg)
server.quit()
send_email("Test Subject", "This is a test email body.", "recipient@example.com")
2. Web Scraping
Web scraping involves extracting data from websites. With BeautifulSoup
and requests
, you can gather information from web pages effortlessly.
Script Example:
pythonimport requests
from bs4 import BeautifulSoup
url = "http://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
data = soup.find_all('p') # Extracts all paragraph tags
for p in data:
print(p.text)
3. File Management
Managing files and directories is easy with Python. You can create, move, rename, and delete files using the os
and shutil
modules.
Script Example:
pythonimport os
import shutil
def organize_files(directory):
for filename in os.listdir(directory):
if filename.endswith('.txt'):
shutil.move(os.path.join(directory, filename), os.path.join(directory, 'TextFiles', filename))
elif filename.endswith('.jpg'):
shutil.move(os.path.join(directory, filename), os.path.join(directory, 'Images', filename))
organize_files('/path/to/your/directory')
4. Data Analysis
Python's pandas
library is perfect for data analysis. You can read, manipulate, and analyze large datasets with ease.
Script Example:
pythonimport pandas as pd
data = pd.read_csv('data.csv')
print(data.describe())
5. Social Media Automation
Automating social media posts can save a lot of time. Libraries like tweepy
for Twitter and instabot
for Instagram make this task straightforward.
Script Example:
pythonimport tweepy
def tweet_message(message):
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)
api.update_status(status=message)
tweet_message("Hello, Twitter!")
6. Reminder Notifications
With libraries like plyer
, you can create desktop notifications for reminders.
Script Example:
pythonfrom plyer import notification
def remind_me(title, message):
notification.notify(
title=title,
message=message,
timeout=10
)
remind_me("Meeting Reminder", "You have a meeting at 10 AM.")
7. Data Backup
Automate the backup of important files to a specified location or cloud service using shutil
.
Script Example:
pythonimport shutil
import os
def backup_files(src, dest):
if not os.path.exists(dest):
os.makedirs(dest)
for filename in os.listdir(src):
shutil.copy(os.path.join(src, filename), dest)
backup_files('/path/to/source', '/path/to/destination')
8. Report Generation
Generate reports in various formats (PDF, Excel) using libraries like reportlab
and xlsxwriter
.
Script Example:
pythonimport xlsxwriter
def generate_report(data, filename):
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
row, col = 0, 0
for item in data:
worksheet.write(row, col, item)
row += 1
workbook.close()
generate_report(['Data1', 'Data2', 'Data3'], 'report.xlsx')
9. Image Processing
Process images by resizing, cropping, and filtering using PIL
(Pillow).
Script Example:
pythonfrom PIL import Image
def resize_image(input_image_path, output_image_path, size):
original_image = Image.open(input_image_path)
resized_image = original_image.resize(size)
resized_image.save(output_image_path)
resize_image('input.jpg', 'output.jpg', (800, 600))
10. Web Testing
Automate web testing using selenium
.
Script Example:
pythonfrom selenium import webdriver
def test_login(url, username, password):
driver = webdriver.Chrome()
driver.get(url)
driver.find_element_by_name('username').send_keys(username)
driver.find_element_by_name('password').send_keys(password)
driver.find_element_by_name('submit').click()
test_login('http://example.com/login', 'user', 'pass')
11. API Integration
Integrate with various APIs to fetch or send data using requests
.
Script Example:
pythonimport requests
def get_weather(api_key, city):
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
weather_data = response.json()
print(weather_data)
get_weather('your_api_key', 'London')
12. Database Management
Automate database tasks like fetching, updating, and deleting records using sqlite3
or other database libraries.
Script Example:
pythonimport sqlite3
def fetch_data(db_name, query):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
cursor.execute(query)
data = cursor.fetchall()
conn.close()
return data
print(fetch_data('example.db', 'SELECT * FROM users'))
13. Finance Management
Track your expenses and manage your budget using Python scripts and pandas
.
Script Example:
pythonimport pandas as pd
def track_expenses(file):
df = pd.read_csv(file)
print(df.groupby('Category').sum())
track_expenses('expenses.csv')
14. Task Automation
Automate repetitive tasks such as moving files, sending emails, or any daily routine.
Script Example:
pythonimport os
import shutil
def move_files(source, destination, file_extension):
for filename in os.listdir(source):
if filename.endswith(file_extension):
shutil.move(os.path.join(source, filename), destination)
move_files('/path/to/source', '/path/to/destination', '.txt')
15. Weather Forecasting
Fetch and display weather forecasts using public APIs.
Script Example:
pythonimport requests
def get_weather(city, api_key):
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
data = response.json()
print(f"Weather in {city}: {data['weather'][0]['description']}")
get_weather('New York', 'your_api_key')
16. Personal Assistant
Create a personal assistant to manage your daily tasks and provide information.
Script Example:
pythonimport pyttsx3
import speech_recognition as sr
def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def listen():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = recognizer.listen(source)
try:
text = recognizer.recognize_google(audio)
print(f"You said: {text}")
return text
except sr.UnknownValueError:
print("Sorry, I did not understand that.")
return ""
speak("How can I help you today?")
command = listen()
17. Network Monitoring
Monitor your network using Python scripts and libraries like psutil
.
Script Example:
pythonimport psutil
def monitor_network():
net_io = psutil.net_io_counters()
print(f"Bytes sent: {net_io.bytes_sent}")
print(f"Bytes received: {net_io.bytes_recv}")
monitor_network()
These scripts demonstrate the versatility and power of Python in automating a wide array of tasks. By incorporating these scripts into your daily workflow, you can save time and focus on more critical activities.
Chart: Automation Script Usage
Below is a simple chart illustrating the frequency of usage of these automation scripts in my daily routine:
plaintextScripts | Usage Frequency --------------------------------|---------------- Email Automation | High Web Scraping | High File Management | Medium Data Analysis | High Social Media Automation | Medium Reminder Notifications | Low Data Backup | Medium Report Generation | Medium Image Processing | Low Web Testing | Low API Integration | High Database Management | Medium Finance Management | High Task Automation | High Weather Forecasting | Medium Personal Assistant | Low Network Monitoring | Low
By leveraging Python's powerful libraries and simple syntax, these automation scripts can transform your daily tasks, making your workflow more efficient and productive.
Comments
Post a Comment