Transforming Your Daily Life: Automate Tasks with Python
Written on
Chapter 1: The Power of Automation
In today's rapidly evolving environment, automating repetitive tasks can significantly enhance productivity. By utilizing Python, a highly adaptable and approachable programming language, I've optimized numerous elements of my everyday life. This guide introduces you to 101 practical Python scripts aimed at automating daily tasks, allowing you to reclaim precious time and concentrate on what truly counts.
Start Automating Your Life Using Python! (File Management with Python Tutorial)
Section 1.1: Renaming Files in a Directory
Effortlessly rename files within a directory using the script below:
import os
def rename_files(directory, prefix):
for count, filename in enumerate(os.listdir(directory)):
new_name = f"{prefix}_{count}.txt"
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
rename_files('/path/to/your/directory', 'file')
Section 1.2: Sending Automated Emails
Implement the following script to send automated emails:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, body, to_email):
from_email = '[email protected]'
password = 'your_password'
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, to_email, msg.as_string())
send_email('Test Subject', 'This is a test email', '[email protected]')
Section 1.3: Backing Up Files
Automatically create backups of your files to a designated directory:
import shutil
import os
def backup_files(source_dir, backup_dir):
for filename in os.listdir(source_dir):
shutil.copy(os.path.join(source_dir, filename), backup_dir)
backup_files('/path/to/source_dir', '/path/to/backup_dir')
Section 1.4: Web Scraping for Latest News
Extract the most recent news headlines from a website:
import requests
from bs4 import BeautifulSoup
def get_latest_news(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
headlines = [item.text for item in soup.find_all('h2')]
return headlines
for item in news:
print(item)
Section 1.5: Automating Social Media Posts
Schedule and publish updates to your Twitter account:
import tweepy
def post_tweet(message):
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)
api.update_status(message)
post_tweet('Automating my life with Python!')
Section 1.6: Generating Daily Reports
Create and save daily reports in a CSV format:
import csv
from datetime import datetime
def generate_report(data, filename):
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Date', 'Data'])
for item in data:
writer.writerow([datetime.now().strftime('%Y-%m-%d'), item])
generate_report(['data1', 'data2', 'data3'], 'daily_report.csv')
Section 1.7: Handling Calendar Events
Automatically add events to your Google Calendar:
from googleapiclient.discovery import build
from google.oauth2 import service_account
def add_event_to_calendar(summary, start_time, end_time):
SCOPES = ['']
SERVICE_ACCOUNT_FILE = 'path/to/service.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)service = build('calendar', 'v3', credentials=credentials)
event = {
'summary': summary,
'start': {
'dateTime': start_time,
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': end_time,
'timeZone': 'America/Los_Angeles',
},
}
event = service.events().insert(calendarId='primary', body=event).execute()
print(f'Event created: {event.get("htmlLink")}')
add_event_to_calendar('Meeting', '2024-09-01T10:00:00', '2024-09-01T11:00:00')
Section 1.8: Monitoring Website Changes
Check for updates on a website:
import hashlib
import requests
def check_website_change(url, old_hash):
response = requests.get(url)
current_hash = hashlib.md5(response.text.encode()).hexdigest()
return current_hash != old_hash
old_hash = 'previous_hash_value'
if check_website_change(url, old_hash):
print('Website has changed!')
Section 1.9: Setting Up Reminders
Send email reminders at specific intervals:
import time
import smtplib
from email.mime.text import MIMEText
def send_reminder(email, subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = '[email protected]'
msg['To'] = email
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login('[email protected]', 'your_password')
server.send_message(msg)
def schedule_reminder(email, subject, body, interval):
time.sleep(interval)
send_reminder(email, subject, body)
schedule_reminder('[email protected]', 'Reminder', 'This is your scheduled reminder.', 3600)
Section 1.10: Cleaning Up Disk Space
Identify and remove large files to free up disk space:
import os
def clean_disk_space(directory, size_limit):
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath) and os.path.getsize(filepath) > size_limit:
os.remove(filepath)
print(f"Deleted {filename}")
clean_disk_space('/path/to/directory', 10000000) # Files larger than 10MB
By automating these tasks, you can significantly enhance your daily routine, alleviate stress, and allocate more time for the activities you love. Python's straightforwardness and robust capabilities make it an ideal tool for achieving these efficiencies. Happy coding!
Chapter 2: Advanced Automation Techniques
Automating My Life with Python: The Ultimate Guide | Code With Me