Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Projects

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Projects

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python Automation Laboratory Exercises

Table of Contents
1. File Organizer
2. Email Automation
3. Web Scraper
4. Expense Tracker
5. Weather App

Instruction:
1. Setup:

Ensure Python 3.x is installed on your system.


Install any required modules using pip (e.g., requests, beautifulsoup4).
Open your preferred code editor or IDE.

2. Project Development:

Follow the detailed steps provided for each project.


Write and test your code to ensure it works as expected.
Document your code with comments to explain your logic and steps.

3. Submission

Upload your script to a GitHub repository.


Submit the link to your GitHub repository.

Objective
The objective of these exercises is to enhance your Python programming skills by working on practical automation
projects. Each project is designed to help you:

Understand and apply Python modules and libraries.


Develop problem-solving skills by automating common tasks.
Gain hands-on experience with file handling, web scraping, email automation, and API usage.
Improve your ability to write clean, efficient, and well-documented code.

By completing these projects, you will build a solid foundation in Python programming and be better prepared to
tackle more complex automation tasks in the future.

Projects
1. File Organizer
Objective
Create a Python script that organizes files in a specified directory into subdirectories based on their file types.

Prerequisites
Basic knowledge of Python programming
Understanding of file handling in Python
Familiarity with the os and shutil modules

Resources
Python 3.x
os and shutil modules (pre-installed with Python)

Instructions
1. Setup:

Ensure Python is installed on your system.


Open your preferred code editor or IDE.

2. Directory Structure:

Choose a directory you want to organize. For example C:\Users\YourName\Downloads .

3. Script Development:

Scan the directory for files.


Create subdirectories for each file type (e.g., Images, Documents, Videos).
Move files into their respective subdirectories.

4. Sample Code

import os
import shutil

# Define the directory to organize


directory = r'C:\Users\YourName\Downloads'

# Define the file type categories and their corresponding extensions


file_types = {
'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
'Documents': ['.pdf', '.docx', '.txt', '.xlsx', '.pptx'],
'Videos': ['.mp4', '.mov', '.avi', '.mkv'],
'Music': ['.mp3', '.wav', '.aac'],
'Archives': ['.zip', '.rar', '.tar', '.gz']
}

# Create subdirectories if they don't exist


for folder in file_types.keys():
folder_path = os.path.join(directory, folder)
if not os.path.exists(folder_path):
os.makedirs(folder_path)

# Move files to their respective subdirectories


for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
file_extension = os.path.splitext(filename)[1].lower()
for folder, extensions in file_types.items():
if file_extension in extensions:
shutil.move(file_path, os.path.join(directory, folder, filename))
break

5. Execution
Save the script as file_organizer.py .
Open a terminal or command prompt.
Navigate to the directory where the script is saved.
Run the script using python file_organizer.py .

2. Email Automation
Objective
Create a Python script that sends automated emails based on specific criteria.

Prerequisites
Basic knowledge of Python programming
Understanding of email protocols (SMTP)
Familiarity with the smtplib and email modules

Resources
Python 3.x
smtplib and email modules (pre-installed with Python)
An email account for sending emails

Instructions
1. Setup:

Ensure Python is installed on your system.


Open your preferred code editor or IDE.

2. Email Configuration:

Set up an email account for sending emails.


Obtain the SMTP server details for your email provider.

3. Script Development:

Create a function to send emails using the smtplib and email modules.
Automate the sending of emails based on certain conditions (e.g., sending reminders).

4. Sample Code:

import smtplib
from email.mime.text import MIMEText

def send_email(to_address, subject, message):


from_address = 'your_email@example.com'
password = 'your_password'
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = from_address
msg['To'] = to_address

with smtplib.SMTP_SSL('smtp.example.com', 465) as server:


server.login(from_address, password)
server.sendmail(from_address, to_address, msg.as_string())

# Example usage
send_email('recipient@example.com', 'Test Subject', 'This is a test email.')

Execution:
Save the script as email_automation.py .
Open a terminal or command prompt.
Navigate to the directory where the script is saved.
Run the script using python email_automation.py .

3. Web Scraper
Objective
Create a Python script that scrapes data from a website and saves it to a file.

Prerequisites
Basic knowledge of Python programming
Understanding of HTML and web scraping techniques
Familiarity with the requests and BeautifulSoup modules

Resources
Python 3.x
requests and BeautifulSoup modules
Install using pip install requests beautifulsoup4

Instructions
1. Setup:

Ensure Python is installed on your system.


Open your preferred code editor or IDE.

2. Website Selection:

Choose a website to scrape.


Identify the HTML elements containing the data you want to extract.

3. Script Development:

Use the requests module to fetch the HTML content.


Use the BeautifulSoup module to parse the HTML content.
Extract the desired data and save it to a CSV file.

4. Sample Code:

import requests
from bs4 import BeautifulSoup
import csv

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

data = []
for item in soup.find_all('div', class_='item'):
title = item.find('h2').text
price = item.find('span', class_='price').text
data.append([title, price])

with open('data.csv', 'w', newline='') as file:


writer = csv.writer(file)
writer.writerow(['Title', 'Price'])
writer.writerows(data)

Execution:
Save the script as web_scraper.py .
Open a terminal or command prompt.
Navigate to the directory where the script is saved.
Run the script using python web_scraper.py .

4. Expense Tracker
Objective
Create a Python script that tracks your expenses and generates a summary report.

Prerequisites
Basic knowledge of Python programming
Understanding of file handling and CSV operations in Python
Familiarity with the csv module

Resources
Python 3.x
csv module (pre-installed with Python)

Instructions
1. Setup:
Ensure Python is installed on your system.
Open your preferred code editor or IDE.
2. Expense Logging:
Create a function to log expenses.
Store the expenses in a CSV file.

3. Report Generation:
Create a function to read the CSV file and generate a summary report.

4. Script Development:
Implement the logging and reporting functions.

5. Sample Code:

import csv
from datetime import datetime

def log_expense(amount, category, description):


with open('expenses.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([datetime.now(), amount, category, description])

def generate_report():
with open('expenses.csv', 'r') as file:
reader = csv.reader(file)
total = 0
for row in reader:
total += float(row[1])
print(f'Total Expenses: ${total:.2f}')

# Example usage
log_expense(50, 'Groceries', 'Bought fruits and vegetables')
generate_report()

Execution:
Save the script as expense_tracker.py .
Open a terminal or command prompt.
Navigate to the directory where the script is saved.
Run the script using python expense_tracker.py .

5. Weather App
Objective
Create a Python script that fetches and displays the current weather for a given location.

Prerequisites
Basic knowledge of Python programming
Understanding of API usage and JSON handling in Python
Familiarity with the requests module

Resources
Python 3.x
requests module
Install using pip install requests

Weather API (e.g., OpenWeatherMap)

Instructions
1. Setup:
Ensure Python is installed on your system.
Open your preferred code editor or IDE.

2. API Configuration:
Sign up for a weather API (e.g., OpenWeatherMap).
Obtain an API key.

3. Script Development:
Use the requests module to fetch weather data from the API.
Parse the JSON response and display the weather information.

4. Sample Code:

import requests

def get_weather(city):
api_key = 'your_api_key'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=
{api_key}&units=metric'
response = requests.get(url)
data = response.json()
if data['cod'] == 200:
weather = data['weather'][0]['description']
temp = data['main']['temp']
print(f'Weather in {city}: {weather}, {temp}°C')
else:
print(f'City {city} not found.')

# Example usage
get_weather('Manila')

Execution:
Save the script as weather_app.py .
Open a terminal or command prompt.
Navigate to the directory where the script is saved.
Run the script using python weather_app.py

You might also like