🐍 Python Tutorial: Automation and Scripting
Python is a powerful language for automating repetitive tasks and building useful scripts to simplify your workflow. In this section, you'll learn how to automate file operations, interact with web pages, schedule tasks, and more.
1. Automating File Operations
You can use Python to rename files, move them between folders, or even parse and modify their contents:
import os
for filename in os.listdir("./docs"):
if filename.endswith(".txt"):
new_name = "processed_" + filename
os.rename(f"./docs/{filename}", f"./processed/{new_name}")2. Web Automation with Selenium
Selenium allows you to control a web browser using Python. It's great for scraping data or automating form submissions:
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get("https://example.com")
search_box = browser.find_element(By.NAME, "q")
search_box.send_keys("Python automation")
search_box.submit()3. Task Scheduling
You can schedule your scripts to run periodically using Python with external tools or libraries like schedule:
import schedule
import time
def job():
print("Running scheduled task")
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)4. Email Automation
Automate sending emails using the built-in smtplib module:
import smtplib
server = smtplib.SMTP("smtp.example.com", 587)
server.starttls()
server.login("you@example.com", "password")
message = "Subject: Hello!
This is an automated email."
server.sendmail("you@example.com", "recipient@example.com", message)
server.quit()