5 Practical Python Scripts for Everyday Tasks: Boost Productivity with Automation
Python’s simplicity and vast ecosystem of libraries make it ideal for automating repetitive tasks. Whether you’re a developer, data analyst, or casual user, these 5 scripts solve common problems efficiently. Let’s dive into each with code examples and use cases.
1. File Organizer: Sort Files by Extension
Problem: Cluttered downloads or desktop folders with mixed file types (PDFs, images, docs).
Solution: A script that automatically moves files into subfolders based on their extensions.
pythonimport os import shutil def organize_files(directory): # Supported file types and their target folders folders = { 'images': ['.jpg', '.jpeg', '.png', '.gif'], 'documents': ['.pdf', '.docx', '.txt'], 'archives': ['.zip', '.rar', '.tar'], 'code': ['.py', '.js', '.html', '.css'] } # Create folders if they don't exist for folder in folders.keys(): os.makedirs(os.path.join(directory, folder), exist_ok=True) # Move files for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isfile(file_path): for folder, extensions in folders.items(): if any(filename.lower().endswith(ext) for ext in extensions): shutil.move(file_path, os.path.join(directory, folder, filename)) break # Usage organize_files(r'C:\Users\YourName\Downloads') # Replace with your path
Key Features:
- Uses
os
andshutil
for file operations. - Handles multiple file types with a dictionary.
- Skips directories and only moves files.
2. Web Scraper: Extract Product Prices from E-commerce Sites
Problem: Manually checking prices across multiple websites is time-consuming.
Solution: A script that scrapes product prices using requests
and BeautifulSoup
.
pythonimport requests from bs4 import BeautifulSoup def scrape_prices(url, product_class): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' } try: response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') prices = soup.find_all(class_=product_class) # Adjust selector as needed for price in prices[:5]: # Print first 5 results print(f"Price: {price.get_text(strip=True)}") except Exception as e: print(f"Error scraping {url}: {e}") # Example: Scrape Amazon (adjust class name) scrape_prices('https://www.amazon.com/s?k=laptop', 'a-price-whole')
Key Features:
- Includes a
User-Agent
header to avoid blocking. - Uses CSS selectors to target price elements.
- Error handling for robustness.
Note: Always check a website’s robots.txt
and terms of service before scraping.
3. PDF Merger: Combine Multiple PDFs into One
Problem: Merging PDFs manually with Adobe Acrobat is tedious.
Solution: A script using PyPDF2
to merge files in seconds.
pythonfrom PyPDF2 import PdfMerger import os def merge_pdfs(folder_path, output_filename): merger = PdfMerger() for filename in os.listdir(folder_path): if filename.lower().endswith('.pdf'): file_path = os.path.join(folder_path, filename) merger.append(file_path) merger.write(os.path.join(folder_path, output_filename)) merger.close() print(f"Merged PDF saved as {output_filename}") # Usage merge_pdfs(r'C:\Users\YourName\Documents\PDFs', 'combined.pdf')
Key Features:
- Processes all PDFs in a folder recursively.
- Preserves original page order.
- Lightweight alternative to GUI tools.
4. Auto Email Sender: Send Personalized Emails at Scale
Problem: Sending hundreds of emails manually is error-prone.
Solution: A script using smtplib
and email.mime
to automate bulk emails.
pythonimport smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import pandas as pd def send_bulk_emails(csv_path, subject, template): # Load recipient data (e.g., name, email) df = pd.read_csv(csv_path) # SMTP settings (replace with your credentials) smtp_server = 'smtp.gmail.com' smtp_port = 587 sender_email = 'your_email@gmail.com' password = 'your_password' # Use environment variables in production! with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(sender_email, password) for _, row in df.iterrows(): msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = row['email'] msg['Subject'] = subject # Personalize email body body = template.format(name=row['name']) msg.attach(MIMEText(body, 'plain')) server.send_message(msg) print(f"Sent to {row['email']}") # Example usage template = """Hi {name}, Thank you for your interest in our service! Best regards, Team""" send_bulk_emails('recipients.csv', 'Welcome Offer', template)
Key Features:
- Uses Pandas for CSV handling.
- Supports HTML/plain text emails.
- Secure TLS encryption for SMTP.
Security Tip: Store credentials in environment variables or a .env
file.
5. Password Generator: Create Strong, Random Passwords
Problem: Weak passwords compromise security.
Solution: A script generating cryptographically secure passwords with secrets
.
pythonimport secrets import string def generate_password(length=12, use_symbols=True): chars = string.ascii_letters + string.digits if use_symbols: chars += '!@#$%^&*' password = ''.join(secrets.choice(chars) for _ in range(length)) return password # Generate and print 5 passwords for _ in range(5): print(generate_password())
Key Features:
- Uses
secrets
(safer thanrandom
for cryptography). - Customizable length and symbol inclusion.
- No external dependencies.
Conclusion: Why Automate with Python?
These scripts demonstrate Python’s power in solving everyday problems:
- File Organizer: Saves hours of manual sorting.
- Web Scraper: Enables price tracking without ads.
- PDF Merger: Replaces expensive software.
- Email Sender: Streamlines marketing campaigns.
- Password Generator: Enhances cybersecurity.
Next Steps:
- Modify scripts to fit your workflow (e.g., add GUI with
tkinter
). - Schedule tasks with
cron
(Linux) or Task Scheduler (Windows). - Explore libraries like
openpyxl
(Excel),selenium
(browser automation), orfastapi
(API development).
Happy automating! 🚀
评论
发表评论