🤖 Python Tutorial — Automation with Python (Beginner to Advanced)
Introduction 🌟
Python is one of the best languages for automation — from automating files and emails to browser tasks, APIs, Excel, and more. In this tutorial, you'll learn how to automate the most common real-world tasks using Python.
Note
💡 Automate repetitive work
💡 Save time & increase productivity
💡 Integrate with scripts, cron jobs, cloud services
💡 Save time & increase productivity
💡 Integrate with scripts, cron jobs, cloud services
1. Automating Files & Folders 📁
List Files
list_files.py
import os
files = os.listdir(".")
print(files)Create Folders
create_folder.py
os.makedirs("new_folder", exist_ok=True)Move / Rename Files
move_rename.py
import shutil
shutil.move("old.txt", "backup/old.txt")
os.rename("file1.txt", "file2.txt")Delete Files
delete_file.py
os.remove("unwanted.txt")2. Automating Excel & CSV 📊
Read CSV
read_csv.py
import csv
with open("data.csv") as f:
for row in csv.reader(f):
print(row)Write CSV
write_csv.py
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Sathish", 25])Excel Automation
excel_openpyxl.py
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
sheet["A1"] = "Hello"
wb.save("excel.xlsx")Note
✔ For advanced tasks, use pandas for data automation.
3. Automating Web Tasks (Selenium) 🌐
selenium_login.py
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://example.com/login")
driver.find_element("id", "user").send_keys("admin")
driver.find_element("id", "pass").send_keys("123")
driver.find_element("id", "login").click()✔ Automate typing, clicking, form submission
4. Automating APIs 🌍
api_automation.py
import requests
users = requests.get("https://jsonplaceholder.typicode.com/users").json()
for u in users:
print(u["name"])5. Automating Emails ✉️
Send Email with SMTP
send_email.py
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("Hello from Python!")
msg["Subject"] = "Automation Test"
msg["From"] = "you@example.com"
msg["To"] = "friend@example.com"
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login("you@example.com", "password")
server.send_message(msg)Note
⚠️ For Gmail, use App Passwords.
6. Automating PDFs 📕
Read PDF
read_pdf.py
import PyPDF2
reader = PyPDF2.PdfReader("sample.pdf")
for page in reader.pages:
print(page.extract_text())Create PDF
write_pdf.py
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Hello PDF!", ln=1)
pdf.output("output.pdf")7. Automating Images 🖼️
image_resize.py
from PIL import Image
img = Image.open("photo.jpg")
img = img.resize((400, 400))
img.save("resized.jpg")8. Automating System Tasks ⚙️
Run Commands
run_command.py
import subprocess
subprocess.run(["echo", "Hello"])Schedule Tasks
- Windows → Task Scheduler
- Linux/Mac → cron jobs
9. Automating Keyboard & Mouse (pyautogui) 🖱️⌨️
pyautogui_example.py
import pyautogui
pyautogui.moveTo(100, 200)
pyautogui.click()
pyautogui.typewrite("Hello Automation", interval=0.1)Note
✔ Useful for GUI automation
10. Automating Notifications 🔔
notification.py
from plyer import notification
notification.notify(
title="Reminder",
message="Drink water!",
timeout=3
)11. Automating Browser Downloads 📥
download.py
import requests
url = "https://example.com/file.zip"
open("file.zip", "wb").write(requests.get(url).content)12. Automating Databases 🗄️
db_insert.py
import sqlite3
conn = sqlite3.connect("auto.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS logs(msg TEXT)")
cur.execute("INSERT INTO logs VALUES ('Script started')")
conn.commit()13. Full Automation Example — Daily Report Bot 📊
daily_bot.py
import requests, csv, smtplib
from email.mime.text import MIMEText
# Step 1: Fetch API data
data = requests.get("https://jsonplaceholder.typicode.com/users").json()
# Step 2: Write CSV
with open("report.csv", "w") as f:
w = csv.writer(f)
w.writerow(["Name", "Email"])
for d in data:
w.writerow([d["name"], d["email"]])
# Step 3: Send email
msg = MIMEText("Report generated and attached.")
msg["Subject"] = "Daily Report"
msg["From"] = "you@example.com"
msg["To"] = "admin@example.com"}
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login("you@example.com", "password")
server.send_message(msg)✔ Automates fetching → processing → notifying
Automation Cheat Sheet 📘
| Task | Library |
|---|---|
| Files | os, shutil |
| Excel | openpyxl, pandas |
| Web automation | Selenium |
| API | requests |
| smtplib | |
| PyPDF2, FPDF | |
| Images | Pillow |
| Mouse/Keyboard | pyautogui |
Best Practices 💡
- ✔ Schedule automation (cron/Task Scheduler)
- ✔ Log every automation step
- ✔ Handle errors with try/except
- ✔ Use environment variables for passwords
- ✔ Use headless mode for Selenium automation
Conclusion 🎉
>>“Automation turns hours of work into seconds — Python gives you superpowers to automate everything.” ✨
You now understand Automation with Python! Want the next topic? Try RPA (Robotic Process Automation), Selenium Advanced, Scrapy, FastAPI Automation, or API Bots. Just tell me! 😊