Give 2 real life usecases of automation with python with code and files I can use now in my laptop
Sure! Here are two real-life use cases of automation with Python that you can try on your laptop. Each example includes code and instructions on how to set it up.
This script will automate the process of sending an email using Python. You will need to have an email account (e.g., Gmail) and enable "Less secure app access" if you're using Gmail.
smtplib
and email
libraries (these are part of the Python standard library, so no need to install them separately).import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email):
from_email = "[email protected]"
from_password = "your_password"
# Create the email
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Connect to the server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, from_password)
# Send the email
server.send_message(msg)
server.quit()
if __name__ == "__main__":
subject = "Test Email"
body = "This is a test email sent from a Python script."
to_email = "[email protected]"
send_email(subject, body, to_email)
[email protected]
and your_password
with your actual email and password.[email protected]
with the recipient's email address.This script will automate the process of renaming multiple files in a directory based on a specific pattern.
os
library (part of the Python standard library).import os
def rename_files(directory, prefix):
for count, filename in enumerate(os.listdir(directory)):
dst = f"{prefix}_{str(count).zfill(3)}{os.path.splitext(filename)[1]}"
src = f"{directory}/{filename}"
dst = f"{directory}/{dst}"
# Rename the file
os.rename(src, dst)
if __name__ == "__main__":
directory = "path_to_your_directory"
prefix = "new_name"
rename_files(directory, prefix)
path_to_your_directory
with the path to the directory containing the files you want to rename.new_name
with the prefix you want to use for the new filenames.path_to_your_directory/
file1.txt
file2.txt
file3.txt
path_to_your_directory/
new_name_000.txt
new_name_001.txt
new_name_002.txt
These scripts should help you get started with automating tasks on your laptop using Python.