Python Automation Scripts

Introduction

Python is one of the most powerful languages for automation. Automate files, folders, emails, APIs, tasks, reports, screenshots, and third-party services in a few lines of code.

1. Automating File Operations

import os
import shutil

# create folder
os.makedirs("backup", exist_ok=True)

# copy file
shutil.copy("data.txt", "backup/data.txt")

# list files
print(os.listdir("."))
    

2. Automating Folder Cleanup

import os

for f in os.listdir("logs"):
    if f.endswith(".log"):
        os.remove(os.path.join("logs", f))
    

3. Automating Downloads (Requests)

import requests

url = "https://example.com/file.jpg"
r = requests.get(url)

with open("image.jpg", "wb") as f:
    f.write(r.content)
    

4. Automating Web Scraping

from bs4 import BeautifulSoup
import requests

html = requests.get("https://example.com").text
soup = BeautifulSoup(html, "html.parser")

for h in soup.find_all("h2"):
    print(h.text)
    

5. Automating Email Sending

import smtplib
from email.mime.text import MIMEText

msg = MIMEText("Daily report attached.")
msg["Subject"] = "Report"
msg["From"] = "you@example.com"
msg["To"] = "target@example.com"

with smtplib.SMTP("smtp.gmail.com", 587) as s:
    s.starttls()
    s.login("you@example.com", "password")
    s.send_message(msg)
    

6. Automating Excel Reports (openpyxl)

from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws["A1"] = "Name"
ws["B1"] = "Score"
ws.append(["Kaloyan", 99])

wb.save("report.xlsx")
    

7. Automating Screenshots

import pyautogui

screenshot = pyautogui.screenshot()
screenshot.save("screen.png")
    

8. Automating Keyboard/Mouse

import pyautogui

pyautogui.write("Hello world!")
pyautogui.press("enter")
    

9. Automating APIs

import requests

data = requests.get("https://jsonplaceholder.typicode.com/posts").json()
print(data[0])
    

10. Automating ZIP Backups

import shutil

shutil.make_archive("backup", "zip", "project_folder")
    

11. Automating Scheduled Tasks (Python)

import time

while True:
    print("Task executed")
    time.sleep(60)
    

12. Automating System Commands

import subprocess

subprocess.run(["ping", "8.8.8.8"])
    

13. Automating JSON

import json

with open("data.json") as f:
    data = json.load(f)

data["status"] = "updated"

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)
    

14. Automating Telegram Bots

import telebot

bot = telebot.TeleBot("TOKEN")

@bot.message_handler(commands=["start"])
def start(msg):
    bot.reply_to(msg, "Automation bot active.")

bot.polling()
    

15. Summary