DEV Community

Max Klein
Max Klein

Posted on

Python Automation: 12 Scripts That Save Hours Every Week

Imagine spending 10 hours a week manually renaming files, formatting spreadsheets, or copying data between applications. Now imagine cutting that time down to minutes with a few lines of Python code.

Automation isn't just a productivity hack—it's a game-changer. Python, with its simplicity and power, is the perfect tool for this mission. In this tutorial, I'll walk you through 12 real-world Python scripts that can transform your workflow.


1. Automate File Renaming

import os

folder_path = "path/to/your/files"
prefix = "report_"

for filename in os.listdir(folder_path):
    if os.path.isdir(os.path.join(folder_path, filename)):
        continue
    new_name = prefix + filename
    os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_name))
Enter fullscreen mode Exit fullscreen mode

2. Organize Files by Extension

import shutil, os

source = "path/to/files"
for filename in os.listdir(source):
    _, ext = os.path.splitext(filename)
    dest = os.path.join(source, ext.lstrip('.') or 'other')
    os.makedirs(dest, exist_ok=True)
    shutil.move(os.path.join(source, filename), os.path.join(dest, filename))
Enter fullscreen mode Exit fullscreen mode

3. Web Scraping with BeautifulSoup

import requests
from bs4 import BeautifulSoup

url = "https://example.com/products"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for product in soup.find_all('div', class_='product'):
    name = product.find('h2').text.strip()
    price = product.find('span', class_='price').text.strip()
    print(f'{name}: {price}')
Enter fullscreen mode Exit fullscreen mode

4. Automate Email Sending

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('Automated report attached.')
msg['Subject'] = 'Weekly Report'
msg['From'] = 'you@gmail.com'
msg['To'] = 'recipient@example.com'

with smtplib.SMTP('smtp.gmail.com', 587) as s:
    s.starttls()
    s.login('you@gmail.com', 'app_password')
    s.send_message(msg)
Enter fullscreen mode Exit fullscreen mode

5. Schedule Tasks with APScheduler

from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime

def job():
    print(f'Task executed at {datetime.now()}')

scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', minutes=5)
scheduler.start()
Enter fullscreen mode Exit fullscreen mode

6. Merge CSV Files with Pandas

import pandas as pd

df1 = pd.read_csv('data1.csv')
df2 = pd.read_csv('data2.csv')
merged = pd.merge(df1, df2, on='ID')
merged.to_csv('merged.csv', index=False)
Enter fullscreen mode Exit fullscreen mode

7. Generate Sales Reports

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('sales.csv')
monthly = df.groupby('Month')['Sales'].sum()
monthly.plot(kind='bar', figsize=(10, 6))
plt.title('Monthly Sales')
plt.savefig('report.png')
Enter fullscreen mode Exit fullscreen mode

8. System Backups

import shutil, os
from datetime import datetime

source = 'important_files/'
backup = f'backups/{datetime.now().strftime("%Y%m%d_%H%M%S")}'
shutil.copytree(source, backup)
print(f'Backup created: {backup}')
Enter fullscreen mode Exit fullscreen mode

9. Extract Text from PDFs

import PyPDF2

with open('document.pdf', 'rb') as f:
    reader = PyPDF2.PdfReader(f)
    text = ''.join(page.extract_text() for page in reader.pages)
print(text[:500])
Enter fullscreen mode Exit fullscreen mode

10. Batch Image Conversion

from PIL import Image
import os

for f in os.listdir('images/'):
    if f.endswith('.png'):
        img = Image.open(f'images/{f}')
        img.save(f'images/{f.replace(".png", ".jpg")}', 'JPEG')
Enter fullscreen mode Exit fullscreen mode

11. API Data Fetching

import requests

response = requests.get('https://api.weatherapi.com/v1/current.json', params={'key': 'YOUR_KEY', 'q': 'London'})
data = response.json()
print(f"London: {data['current']['temp_c']}°C")
Enter fullscreen mode Exit fullscreen mode

12. Screenshot Automation

import pyautogui

screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')
Enter fullscreen mode Exit fullscreen mode

Conclusion

By automating even a few tasks, you'll save hours every week. Start small, test thoroughly, and gradually expand your automation toolkit.


Need custom automation or data extraction? Check out N3X1S INTELLIGENCE on Fiverr for professional Python automation and web scraping services.

Top comments (0)