Chapter 18: Automation with Python
Automation with Python enables repetitive tasks to be performed efficiently, saving time and reducing human error. Common use cases include file handling, web scraping, and system monitoring.
File and Directory Automation
Python’s os and shutil modules facilitate file and directory manipulation.
File Management
import os
# Create a new file
with open("example.txt", "w") as file:
file.write("Hello, Automation!")
# Rename a file
os.rename("example.txt", "new_example.txt")
# Delete a file
os.remove("new_example.txt")Directory Management
# Create a directory
os.mkdir("new_folder")
# List contents of a directory
print(os.listdir("."))
# Remove a directory
os.rmdir("new_folder")Copying and Moving Files
Web Scraping
Web scraping extracts data from websites. Python’s requests and BeautifulSoup libraries are commonly used for this purpose.
Installing Dependencies
Example: Scraping Website Data
Handling Dynamic Content
For websites with dynamic content, use selenium.
System Monitoring
System monitoring tasks, such as tracking resource usage or automating backups, can be achieved using Python.
Example: Monitoring CPU and Memory Usage
Scheduling Tasks
The schedule library is used to run tasks at specific intervals.
Automating Emails
Automating emails can be achieved using the smtplib library.
Example: Sending an Email
Exercises
Exercise 1: Automate File Cleanup
Write a script to delete all .tmp files in a directory.
Solution:
Exercise 2: Scrape and Save Data
Scrape titles from a webpage and save them to a file.
Solution:
Exercise 3: Monitor Disk Usage
Write a script to monitor and alert if disk usage exceeds 80%.
Solution:
Best Practices
Use libraries suited to the task for efficiency.
Avoid hardcoding sensitive information like passwords; use environment variables instead.
Test automation scripts in a controlled environment before deploying.
Implement error handling to manage unexpected scenarios.
Document scripts for future reference and maintenance.
In the next chapter, we will explore Python’s role in cloud and DevOps, including writing deployment scripts and working with cloud SDKs.
Last updated