Photo Python

How to Use Python for Beginners to Automate Simple Daily Tasks

You may be wondering, “Can I actually do this, and what’s involved?” if you’ve heard about Python and how it can simplify your life by automating those tedious little tasks you perform on a daily basis. The good news is that you can! Python is an excellent language for novices wishing to experiment with automation.

Here, we’re not talking about developing sophisticated AI or overseeing international financial markets; rather, we’re talking about solving those common annoyances that take up your time. Consider doing things like renaming a number of files, sending out similar emails, or simply keeping an eye out for updates on a website. To get you started on automating your own small area of the digital world, this guide will walk you through the fundamentals with an emphasis on doable actions and real-world examples. You need to set up a few things before you can begin writing code to automate tasks. It’s similar to needing a screwdriver in order to fix something.

If you’re looking to enhance your Python skills further, you might find it helpful to read about how to effectively manage your time and tasks through automation. A related article that explores the importance of productivity in daily life is available at Soaring to New Heights: A Summary of Fourth Wing by Rebecca Yarros. This article provides insights that can complement your journey in using Python to streamline your everyday activities.

It’s not difficult, so don’t worry. Python installation. To begin with, you need Python. The official Python website (python .

org) is the place to obtain it. They offer Linux, macOS, and Windows downloads. Which version: It’s usually best for novices to stick to the most recent stable release, such as Python 3.10 or 3.11. Compatibility problems with older versions may eventually arise.

Installation advice: Make sure to check the “Add Python to PATH” box when installing on Windows. Python is now much simpler to use from the command line thanks to this. Your First IDE (Code Editor). Although you can write Python using a basic text editor, most people find that using an Integrated Development Environment (IDE) or code editor is far more beneficial. These tools have features like error checking & syntax highlighting, which make your code look better and be easier to read.

If you’re just starting with Python and looking to automate simple daily tasks, you might find it helpful to explore some coding exercises that can enhance your skills. A related article that offers valuable insights is available at Python Coding Exercises, which provides various challenges designed to improve your programming abilities. By practicing these exercises, you can gain a deeper understanding of Python and become more proficient in automating tasks efficiently.

VS Code is a very well-liked, powerful, and free option. It has many add-ons, such as linters and debugging tools, that can further improve your Python coding experience. Another great, free option made especially for Python development is PyCharm Community Edition. Although it comes with a few more features than Visual Studio Code for Python, at first it may seem a little overwhelming. IDLE: This comes with Python!

If you’re looking to enhance your skills in automating daily tasks with Python, you might find it helpful to explore how to save money while doing so. A related article discusses various strategies and tools that can help you maximize your budget, making it easier to invest in resources for your programming journey. You can read more about these money-saving tips in this comprehensive guide. By combining your newfound Python skills with smart financial decisions, you can streamline your daily activities without breaking the bank.

It’s very basic, but it’s great for experimenting with short code snippets and getting started. If you want to give it a try right away, this is a good “no installation needed” option. The terminal or command line. Your computer’s command line, also known as Command Prompt/PowerShell on Windows or Terminal on macOS/Linux, will be used to interact with your Python scripts.

Although it may initially seem a bit daunting, this is where your automation scripts work their magic. The fundamental commands you’ll require will be covered. Let’s get started with something tangible. Dealing with files is one of the most frequent daily tasks.

Let’s say you download a large number of files and wish to arrange them into distinct folders. Python can quickly accomplish this. utilizing the OS Module.

Python’s built-in os module, which stands for operating system, allows you to work with the file system on your computer. It’s similar to allowing Python to instruct your computer on how to handle files and folders. establishing folders.

using Python. Open OS. Choose a name for the folder you wish to make.
“My_Automated_Files” is the folder name. Verify whether the folder is already there.

OS . path, if not. exists(folder_name):. os .

makedirs(folder_name). print “Folder ‘{folder_name}’ has been successfully created.”. •). otherwise.
“Folder ‘{folder_name}’ already exists,” is printed. “).

This code determines whether the folder “My_Automated_Files” is present. If it doesn’t, it makes it. Transferring files. using Python. bring in OS.

import shutil To move files, we’ll use shutil. Specify the path to the source & destination. path/to/your/downloaded_document is the source file path. swap out “pdf” for the real path.
“My_Automated_Files” is destination_folder.

os . path . join(destination_folder, os .

path . basename(source_file_path)) equals destination_file_path. Move the document.

Try:. Shutil . move (source_file_path, destination_file_path). print(f) “Moved to ‘{destination_folder}’ from ‘{os . path . basename(source_file_path)}.”. •).

aside from FileNotFoundError. print “Error: Source file ‘{source_file_path}’ not found.”. •). Here’s an example of moving a file. Regardless of your operating system, os . path .

join() securely merges folder & file names, while os . path . basename() only retrieves the file name. Our useful function for moving is shutil . move().

automating the organization of folders. Let’s now combine these to write a script that sorts downloaded files according to their type. Goal: Within your downloads directory, move all .pdf files to a “Documents” folder and all . jpg or .

png files to an “Images” folder. The Configuration:. Make the “Documents” and “Images” subfolders in your Downloads directory. In your Downloads folder, save the Python script.

The script. Python. Obtain OS. Bring in shutil. configuration.

downloads_folder = os . path. Expanduser (“~/Downloads”) retrieves the path to your Downloads folder. os .

path . join(downloads_folder, “Documents”) = document_folder. OS . path .

join(downloads_folder, “Images”) = image_folder. If destination folders don’t already exist, create them. os . makedirs (exist_ok=True, document_folder).

os . makedirs (exist_ok=True, image_folder). print(f”Scanning: {downloads_folder}”). Files are processed.

for the downloads_folder filename in the OS Dot listdir. Build the entire file path. file_path is equal to os . path . join (filename, downloads_folder).

Ignore the script itself or the directory itself. if filename == os . path . basename(__file__) or os .

path . isdir(file_path). Proceed.

Get the extension of the file (e. (g). “,”. pdf”, “dot jpg”). OS .

path is the file extension. splitext(filename). file_extension is the same as file_extension. For simpler comparison, make it lowercase using lower().

Adapt to the extension. if the file’s extension is “. pdf”:.

os . path . join(document_folder, filename) = destination_path. Try it. Shutil .

move(destination_path, file_path).
“Moved ‘{filename}’ to Documents,” print(f). “). with the exception of e:.
“Could not move ‘{filename}’: {e}” is printed. If file_extension is in “dot jpg”, “dot jpeg”, or “dot png”:. destination_path is equal to os .

path . join (filename, image_folder). Try this. shutil . move (destination_path, file_path).
“Moved ‘{filename}’ to Images” was printed. ().

aside from exceptions like e:. print(f”Could not move ‘{filename}’: {e}”). If you’d like, add more categories here! If file_extension isn’t “. “zip.”.

a dot. transfer to a zip file. If file_extension isn’t “. xlsx”:. a dot.

transfer to a folder called Spreadsheets.

“Print”. File organization is finished!”). To use this:. Save the code in a . py file (e.g.

A g. In your Downloads folder, type organize_downloads . py). Launch the command line and go to the Downloads folder (e.g. A g.

cd Downloads), then execute organize_downloads . py in Python. If the “Documents” and “Images” folders don’t already exist, it will create them and move any files that match.

Python can assist if you’re sick of sending out the same emails every week. A built-in module will be used for this. email and the smtplib modules. Email sending modules are part of Python’s standard library.

The email module assists you in creating the email message itself, while smtplib handles the actual sending process over the Simple Mail Transfer Protocol (SMTP). Important Note: Most email providers (such as Gmail and Outlook) require you to do one of two things for security reasons. Instead of using your standard login password, create an “app password.”. Turn on “less secure app access” (although this is being phased out and is generally discouraged). Look up “Gmail app password” in the Google Account settings to access Gmail.

How to Write an Email. In Python. from an email. a mime.

import MIMEText. def create_email(subject, body, sender, and recipient emails):. message = MIMEText (body). message[‘From’] equals sender_email. message[‘To’] = receiver_email.

subject = message[‘Subject’]. reply message. I am sending the email. In Python. Smtplib import. from an email.

The mime. import MIMEText text. send_email (sender_email, sender_password, recipient_email, subject, body, smtp_server, smtp_port):. message = create_email(sender_email, recipient_email, subject, body).

Try this. through smtplib. Server: SMTP (smtp_server, smtp_port). Protect the connection with server .

starttls(). servant. login (sender_password, sender_email). sender_email, recipient_email, message . as_string(), and server .

sendmail().
“Email sent successfully to {receiver_email}!” is printed. except for the exception e:. print (“Failed to send email: {e}”). Example of Use (SUBSTitute with your information!). The sender is “your_email@gmail .

com”. password = “your_app_password” Make use of an app password rather than your personal one!
“recipient_email@example . com” is the receiver.
“Daily Reminder” is the email_subject.

email_body = “Hello.”. An automated reminder has been sent! Finest.

Your Automated Companion. Regarding Gmail:…
“smtp . gmail .

com” is smtp_server_gmail. For SSL, smtp_port_gmail = 465, or 587. send_email (sender, password, recipient, email_body, email_subject, smtp_server_gmail, smtp_port_gmail). In addition to using the appropriate SMTP server & port for your email provider, don’t forget to substitute your real email, app password, and recipient’s email in placeholders.

A Weekly Newsletter Snippet Automated. Let’s say you want to send out a weekly email with a block of text. You can create a script that pulls that text & sends it out to a list of subscribers. The Goal: Send a weekly update email with a pre-written snippet to a small group of people.

The configuration. Get your email provider’s SMTP server and port. Generate an app password for your email account. Have your list of recipient emails ready. The screenplay.

Python. import smtplib. from email. mime. text import MIMEText.

import time To add a short delay between sending to multiple recipients. Your Email Credentials and Server Details . SENDER_EMAIL = “your_email@gmail . com” Your email address. APP_PASSWORD = “your_app_password” Your app-specific password. SMTP_SERVER = “smtp .

gmail . com” e. g. , smtp . gmail . com, smtp.

office365 . com. SMTP_PORT = 587 Typically 587 for STARTTLS, 465 for SSL.

Email Content . EMAIL_SUBJECT = “Weekly Update from the Team”. WEEKLY_SNIPPET = “””.

Hello Team,. Hope you’re all having a productive week! Just a quick update on our ongoing project: We’ve successfully completed the first phase of user testing, and the feedback has been largely positive.

We’re now moving on to phase two, which involves integrating the new analytics dashboard. We anticipate this will be a significant improvement for tracking key metrics. Please take a moment to review the latest progress report attached. Have a great weekend!
“””. List of Recipients . RECIPIENTS = [.
“alice@example .

com”,.
“bob@example . com”,.
“charlie@example . com”,.
]. def create_email_message(sender, recipient, subject, body):.

message = MIMEText(body). message[‘From’] = sender. message[‘To’] = recipient.

message[‘Subject’] = subject. return message. def send_bulk_emails(sender, password, recipients, subject, body, smtp_server, smtp_port):. print(“Starting to send emails. “).

sent_count = 0. try:. with smtplib. SMTP(smtp_server, smtp_port) as server:. server .

starttls(). server. login(sender, password). for recipient in recipients:. email_message = create_email_message(sender, recipient, subject, body).

try:. server . sendmail(sender, recipient, email_message . as_string()). print(f”Sent ‘{subject}’ to {recipient}”).

sent_count += 1. time . sleep(1) Wait 1 second before sending the next email to avoid rate limits. except Exception as e:.

print(f”Failed to send email to {recipient}: {e}”). except Exception as e:. print(f”Error connecting to SMTP server or logging in: {e}”). print(f”. Email sending process finished. {sent_count} emails sent. “).

Execute the script . if __name__ == “__main__”:. Before running, ensure you’ve replaced placeholders with your actual details! Also, consider adding checks to ensure sender details are valid. send_bulk_emails(SENDER_EMAIL, APP_PASSWORD, RECIPIENTS, EMAIL_SUBJECT, WEEKLY_SNIPPET, SMTP_SERVER, SMTP_PORT).

To use this:. Replace SENDER_EMAIL, APP_PASSWORD, SMTP_SERVER, SMTP_PORT, and RECIPIENTS with your own information. Save the script as a . py file (e.

g. , send_weekly . py). Run it from your command line: python send_weekly .

py. Ever wanted to quickly get some information from a website without endless clicking? Python’s web scraping capabilities can be a lifesaver for very specific, repeatable tasks. Introducing requests & BeautifulSoup.

These are two of the most popular libraries for web scraping, and they’re not included in the default Python installation, so you’ll need to install them using pip (Python’s package installer). Installation:. Open your command line & type:. bash.

pip install requests beautifulsoup4. requests: This library makes it super easy to send HTTP requests (like fetching a webpage). BeautifulSoup: This library parses HTML and XML documents, making it easy to navigate and extract data from the page. Extracting a Specific pc\. of Data.

Let’s say you want to obtain the most recent headline from a news website or the price of a particular product from an online retailer. The objective is to retrieve the text content of a particular webpage’s HTML element. The setup. Choose which website you wish to “scrape.”.

Use your browser’s developer tools (usually by right-clicking on an element & selecting “Inspect” or “Inspect Element”) to find the HTML tag and its attributes (like class or id) that contain the data you want. The script. In Python. import queries. Bring in BeautifulSoup from bs4.

def get_website_data(url, element_tag, element_attributes=None):.
(“). specifies an HTML element in order to retrieve data from a website. Args?

url (str): The website’s URL for the scrape. element_tag (str): The element’s HTML tag (e.g. The g. ‘h1’, ‘span’, ‘div’.

element_attributes (dict, optional): An attribute matching dictionary (e.g. The g. ‘class’: ‘product-price’, ‘id’: ‘price’}. sets to None by default. Returns:. str: The text content of the found element, or an error message.
“””.

try:. Send a GET request to the URL. response = requests . get(url, timeout=10) Added timeout for safety.

response. raise_for_status() Raise an exception for bad status codes (4xx or 5xx). Parse the HTML content. soup = BeautifulSoup(response.

text, ‘html . parser’). Find the specific element. if element_attributes:.

found_element = soup . find(element_tag, element_attributes). else:. found_element = soup .

find(element_tag). if found_element:. Return the text content, stripping leading/trailing whitespace. return found_element . get_text(strip=True).

else:. return f”Element with tag ‘{element_tag}’ and attributes {element_attributes} not found. “. except requests. exceptions.

e: RequestException. return f”Error fetching URL {url}: {e}”. except Exception as e:. return f”An unexpected error occurred: {e}”.

Example Usage (REPLACE WITH ACTUAL WEBSITE AND ELEMENT DETAILS!) . website_url = “https://www. example . com/specific-product-page” Replace with a real URL.

target_tag = “span” e. g. , often prices are in spans. target_attributes = {“class”: “price”} e. g. , check the website’s HTML for the correct class. price = get_website_data(website_url, target_tag, target_attributes). print(f”The data we found is: {price}”).

Another Example: Getting the main headline . news_url = “https://www . bbc . com/news” Example.

headline_tag = “h1” Often headlines are in h1 tags. BBC News uses a specific class for its main headline, you’d need to inspect the page to find it. For demonstration, let’s assume it’s “gs-c-promo-heading__title” or similar.

This is a simplified example. Real-world scraping might require more complex selectors. headline_attributes = {“class”: “gs-c-promo-heading__title”}.

Let’s try without specific attributes and hope the first h1 is what we want for this example. main_headline = get_website_data(news_url, headline_tag). print(f”The main headline on BBC News is: {main_headline}”). How to make this practical:. Find a website where you want to extract specific data regularly. To identify the precise HTML tag and data attributes (such as class or id), use the developer tools in your browser.

Enter your results in place of the example website_url, target_tag, and target_attributes. Launch the script. For example, you could have this script email you the data every day. Thus far, we have created scripts that can be manually executed via the command line. The real power of automation comes when these scripts run on their own.

Cron Jobs (Linux/macOS) and Task Scheduler (Windows). Every operating system has a way to schedule tasks. On Linux and macOS: You’ll use cron. How to access: Open your terminal and type crontab -e.

This opens a file where you add lines to schedule jobs. Format: The format is a bit cryptic: minute hour day_of_month month day_of_week command_to_run. Example: To run our organize_downloads . py script every day at 8:00 AM, you’d add a line like this:.

0 8 * /usr/bin/python3 /path/to/your/organize_downloads .

py.

(Make sure /usr/bin/python3 is the correct path to your Python executable and /path/to/your/organize_downloads . py is the full path to your script). On Windows: You’ll use the Task Scheduler. How to access: Search for “Task Scheduler” in the Windows search bar. How to use: It has a graphical interface.

You create a new task, set a trigger (e. g. , daily at a specific time), & then specify the program to run (your Python interpreter) and the arguments (the path to your Python script). Example: You’d configure it to run C:Python310python. exe C:UsersYourNameScriptsorganize_downloads .

py on your desired schedule. A Note on Relative Paths and Permissions. Scripts that are scheduled frequently run from a different working directory or with different permissions than those that are executed manually.

Absolute Paths Are Safer: Generally speaking, absolute paths—such as /home/user/scripts/my_script . py or C:UsersYourNameDocumentsmy_script . py—are preferable to relative ones in scheduled tasks. Permissions: Verify that the task’s user account has the ability to read and write to the files and folders that your script works with.

The purpose of automation scripts is to ensure dependability. What happens if the structure of a website suddenly changes or your internet goes down? Basic Error Handling with try.

except. You’ve seen an attempt. aside from the examples. This is how Python handles circumstances that could lead to your script crashing gracefully.

The idea is to include potentially error-causing code inside a try block. Python prevents the script from ending abruptly by jumping to the except block if an error actually occurs. Particularly vs.

Except in general. Specific: except FileNotFoundError: – catches only errors related to missing files. General: except Exception as e: – catches almost any error. Use this for general cleanup or logging, but be specific when you can for better control. Example Refinement (from file organization):.

python. inside the loop for moving files . try:.

shutil . move(file_path, destination_path). print(f”Moved ‘{filename}’ to Documents. “). except FileNotFoundError:.
“Error: Source file ‘{file_path}’ not found” is printed.

Ignoring. “). PermissionError is an exception. print(f”Error: Permission to move ‘{filename}’ denied.”. skipping. •).

with the exception of e: Catch any additional unforeseen errors. print(\”An unexpected error occurred while moving ‘{filename}’: {e}”). Monitoring and debugging through logging. You won’t see the print statements when your script runs in the background automatically.

Logging is necessary to keep track of what transpired. Python’s built-in logging module is an extremely potent tool. basic configuration. Python.

logging of imports. Set up logging to write data to a file. logging . basicConfig (filename=’automation).

log’, level=logging. INFO. format=’percent(asctime)s – percent(levelname)s – percent(message)s’).

Now use logging: instead of print().
“Starting script” and logging . info. “). tracking. warning: “A possible problem was found.”. “). logging . error (“A critical error occurred!”).

level = logging. WARNING, CRITICAL, ERROR, and INFO messages will be recorded. You can switch this to logging.

During development, use DEBUG for more verbose output. format: Specifies the appearance of each log message. Using our example as an example. Change: in the file organization script. print(f) “Folder ‘{folder_name}’ was successfully created. ().

with:. logging . info(f”Folder ‘{folder_name}’ created successfully. ().

& swap it out.
“Error: Source file ‘{source_file_path}’ not found” is printed. •). alongside:.

logging . error (“Error: Source file ‘{source_file_path}’ not found.”. “). In this manner, you will have an automation in case your scheduled script runs into a problem.

log file in the same directory that describes the specifics of what went wrong and when. You’ve covered a lot of ground, including installing Python, sending emails, using basic file operations, scheduling tasks, performing basic web scraping, & handling errors. This is a good starting point. suggestions for additional automation. Renaming Files in Bulk: To batch rename images, documents, or code files according to patterns, use .os . rename().

Monitoring Website Changes: Send out an email or alert if a particular piece of information on a webpage changes. Downloading Files Automatically: Getting a daily report from a website, for instance. Interacting with APIs: Python can communicate directly with a variety of services that provide APIs (Application Programming Interfaces), such as social media, weather, and stock prices. This is stronger and more sophisticated.

Desktop Organization: Write scripts to transfer new files from your desktop into designated folders. Processing Text Files: Read, analyse, or modify data in .txt or .csv files. Learning Resources. The best resource for learning the basics of Python is the Official Python Tutorial.

Real Python: An excellent website with tons of tutorials & articles for all skill levels. Automate the Boring Stuff with Python: A popular free online book specifically designed for beginners looking to automate tasks. The best way to learn is by doing, so don’t be scared to try new things.

Start with tiny, doable tasks that truly irritate you. You can take on increasingly difficult tasks as your confidence grows. Enjoy automating!
.

Leave a Reply