17. Automation and Scripting in Python

Automation means using programs to perform repetitive tasks automatically.

Python is widely used for automation because it is:

  • Simple
  • Powerful
  • Cross-platform

Automation can save:

  • Time
  • Effort
  • Manual work

Common Automation Tasks

Python can automate:

  • File handling
  • Web scraping
  • Email sending
  • Data entry
  • System tasks
  • Scheduled jobs

Automating Tasks

Python scripts can perform repetitive operations automatically.


Example: Automatic File Creation

with open("notes.txt", "w") as file:
file.write("Python Automation")

Example: Rename Multiple Files

import os

files = os.listdir()

for index, file in enumerate(files):

if file.endswith(".txt"):

new_name = f"file_{index}.txt"

os.rename(file, new_name)

print("Files renamed")

Example: Folder Creation

import os

for i in range(1, 6):

folder_name = f"Folder_{i}"

os.mkdir(folder_name)

print("Folders created")

Web Scraping

Web scraping extracts data from websites.

Popular libraries:

  • Requests
  • BeautifulSoup

Install Libraries

pip install requests beautifulsoup4

Send HTTP Request

import requests

response = requests.get("https://example.com")

print(response.status_code)

Parse HTML with BeautifulSoup

from bs4 import BeautifulSoup

html = """
<html>
<h1>Python</h1>
</html>
"""

soup = BeautifulSoup(html, "html.parser")

print(soup.h1.text)

Output:

Python

Extract All Links

from bs4 import BeautifulSoup

html = """
<a href='https://google.com'>Google</a>
<a href='https://github.com'>GitHub</a>
"""

soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all("a"):
print(link.get("href"))

Scrape Website Title

import requests
from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

soup = BeautifulSoup(
response.text,
"html.parser"
)

print(soup.title.text)

Email Automation

Python can send emails automatically.

Uses:

  • Notifications
  • Reports
  • OTP emails
  • Bulk emails

Using smtplib

import smtplib

Send Simple Email

import smtplib

server = smtplib.SMTP(
"smtp.gmail.com",
587
)

server.starttls()

server.login(
"your_email@gmail.com",
"your_password"
)

message = "Hello from Python"

server.sendmail(
"your_email@gmail.com",
"receiver@gmail.com",
message
)

server.quit()

print("Email sent")

Email with Subject

from email.message import EmailMessage
import smtplib

msg = EmailMessage()

msg["Subject"] = "Python Email"

msg["From"] = "your_email@gmail.com"

msg["To"] = "receiver@gmail.com"

msg.set_content("Hello from Python")

server = smtplib.SMTP(
"smtp.gmail.com",
587
)

server.starttls()

server.login(
"your_email@gmail.com",
"password"
)

server.send_message(msg)

server.quit()

File Automation

Python can automate file operations such as:

  • Copying files
  • Moving files
  • Deleting files
  • Organizing folders

Copy File

import shutil

shutil.copy(
"source.txt",
"destination.txt"
)

Move File

import shutil

shutil.move(
"source.txt",
"new_folder/source.txt"
)

Delete File

import os

os.remove("data.txt")

Organize Files by Extension

import os
import shutil

files = os.listdir()

for file in files:

if file.endswith(".jpg"):

if not os.path.exists("Images"):
os.mkdir("Images")

shutil.move(file, f"Images/{file}")

Scheduling Scripts

Scheduling allows scripts to run automatically at specific times.


Using schedule Library


Install Schedule

pip install schedule

Example Scheduler

import schedule
import time

def task():
print("Task executed")

schedule.every(5).seconds.do(task)

while True:

schedule.run_pending()

time.sleep(1)

Run Daily Task

schedule.every().day.at("10:00").do(task)

System Scheduler

You can also use:

  • Windows Task Scheduler
  • Linux Cron Jobs

Cron Job Example (Linux)

0 10 * * * python3 script.py

Runs script daily at 10:00 AM.


Windows Task Scheduler

Steps:

  1. Open Task Scheduler
  2. Create Basic Task
  3. Select Python script
  4. Set schedule time

Practical Example

Automatic Backup Script

import shutil
import datetime

source = "data.txt"

date = datetime.datetime.now().strftime(
"%Y%m%d_%H%M%S"
)

backup = f"backup_{date}.txt"

shutil.copy(source, backup)

print("Backup created:", backup)

Advantages of Automation

✅ Saves time
✅ Reduces manual work
✅ Improves productivity
✅ Reduces errors
✅ Handles repetitive tasks efficiently


Best Practices

✅ Handle exceptions properly
✅ Avoid hardcoded passwords
✅ Use logging for scripts
✅ Schedule scripts carefully
✅ Respect website scraping policies


Summary

In this chapter you learned:

✅ Automating tasks
✅ Web scraping
✅ Email automation
✅ File automation
✅ Scheduling scripts