Beginner’s Guide To Python Automation Scripts (With Code Examples)

Travis Cuzick
Travis Cuzick
hero image

Are you tired of wasting time on repetitive tasks at work and constantly thinking, “There’s got to be an easier way to do this!?

Good news is that you're not alone, there is a better way, and I'm about to share it with you in this guide.

Imagine if you could automate these mundane activities, allowing you to focus on more creative and impactful work. That's where Python automation scripts come in.

Python, a popular and easy-to-learn programming language, allows you to automate everyday tasks effortlessly - and save literally hundreds of hours of effort!

Not only that, but by using these automations, you can even reduce errors and significantly boost your productivity. Whether you're a complete beginner or have some coding experience, this guide will provide you with the tools to transform your daily routine.

Ready to make your work life easier and more efficient with Python?

Let’s get started!

Sidenote: If you struggle to understand or use this guide, or simply want a deep dive and learn how to create your own custom scripts, then check out my Python automation course.

learn python automation

This course will turn you into an automation wizard that can automate away all the boring, annoying parts of your work and life. You'll learn by being hands-on and building 11 automation projects using Python and AI. All from scratch. No coding experience is required.

I guarantee that this is the best, most comprehensive, and up-to-date course to learn automation. You'll not only learn the fundamental building blocks, but you'll also learn advanced topics, tools, and tricks that most courses don't cover!

Anyways, back to the guide!

What are automation scripts?

Automation scripts are programs that perform repetitive tasks on your computer without needing your intervention each time. Think of them as little digital assistants designed to handle specific, routine jobs that you would otherwise do manually.

It’s a simple concept, but the payoff can be absolutely huge.

For example

Let's say you have a folder full of text files, and you need to rename all of them with a .bak extension so that you can create backup copies. It’s a great habit to backup important data, but doing this manually would be tedious and time-consuming, especially if you had hundreds of files.

But with a Python automation script, you can instruct your computer to handle this task quickly and efficiently.

Don’t worry about the code too much for now, but here's a simple script that does exactly that:

import os

for filename in os.listdir('.'):
	if filename.endswith('.txt'):
    	os.rename(filename, filename + '.bak')

So what’s happening here?

Basically, this script tells your computer to:

  • Look at each file in the current directory (that's what the dot means)
  • Check if each file ends with .txt
  • If it does, rename it by adding .bak to the end

You don't need to understand each line of this script to use it. Just know that with Python, and a little bit of learning, you can turn repetitive tasks like this one into a thing of the past.

There are even other tools out there that we can use alongside this such as GUI tools (more on these later) that can even simplify the code creation process.

The benefits of using Python automation

You might be thinking, “Ok this seems like a cool feature, but it’s probably not worth my time to spend learning about”...

Well, you would be wrong. Dead wrong. In fact, this slight detour to pick up this skill could save you literally hundreds of hours per year.

Which brings me to benefit one on this list.

#1. Automations save your time and money

One of the main benefits of automation is that it saves time. Simply because, instead of performing the same tasks over and over again, you write a script once, and it does the work for you.

You can then focus on more complex and creative tasks.

For example

I used to receive daily sales reports via email and needed to copy the data into a spreadsheet.

  • This task took about 15 minutes each day, which doesn’t seem like much
  • However, over a month, this added up to roughly 7.5 hours of dull, repetitive work
  • Over a year though that's 94 hours, or around 2 ½ weeks!

But with a Python automation script, I could extract the data from these emails and automatically update the spreadsheet. Just a few clicks and I was done.

Over a year, this saved me around 90 hours - a significant time saving that I could use for more important tasks or to learn new skills, like more advanced coding.

Mind blown?

Just think of the impact this could have:

  • If you work for yourself, how much time and money could you be saving so that you’re working on other important tasks?
  • If you work for a company, how much easier would your day job be if you were doing this?
  • Heck, what would be the impact if you did this for multiple repetitive tasks…

#2. Automations reduce errors

Mistakes happen, and even the most meticulous of us can mess up when performing repetitive tasks.

However, Python automation removes the possibility of human error, ensuring that the task is performed accurately every time. The machine always does the same thing so zero mistakes and typos.

#3. Automation enhances your productivity

With the mundane tasks taken care of, you have more energy for tasks that truly need your attention and skills. This leads to better productivity and efficiency.

#4. Python automations are fairly easy to learn

Python's straightforward syntax is easy to pick up even for beginners. This makes it a popular choice for non-programmers who are looking to dip their toes into the world of coding.

(It’s literally one of 2 options that we recommend for absolute beginners learning to code).

For example

Let’s look at the example script from earlier:

import os

for filename in os.listdir('.'):
	if filename.endswith('.txt'):
    	os.rename(filename, filename + '.bak')

Notice how the code is kind of similar to normal language? You can probably guess what’s happening on each line, but let’s break it down.

  • import os is kind of like saying "I need the operating system's help for a task"
  • for filename in os.listdir('.') is basically saying "for each file name in the current directory"
  • if filename.endswith('.txt') means "if the file name ends with '.txt'"
  • os.rename(filename, filename + '.bak') translates to "rename the file by adding '.bak' to the end"

Or simply put: Help me computer and do this task. Look at this directory. If the file ends with .txt, change it to .bak.

Better still, Python is also fairly easy to use, as well as understand.

#5. You don’t always have to start from scratch

Python has an extensive range of ‘libraries’, but what does that mean?

Well, in non-tech talk, these are basically databases of pre-written pieces of code that you can use to perform common tasks.

This means you often won't have to start from scratch when automating a task. If there's something you want to do, there's probably a Python library that can help you do it.

Give them a quick search and then test it out. Worst case scenario, you're half way to figuring out your task automation.

#6. These automations work almost anywhere

Python works on all major operating systems like Windows, macOS, and Linux.

So, a Python automation script written on a Windows system will also work just as well on a Mac or Linux system with only a few modifications.

I’ll even show you how to use it on all systems later on.

#7. You can always find help

Python has a large and active community of developers. This means that if you ever run into problems or need to learn something new, there’s a good chance that someone, somewhere, has already found a solution and shared it online.

Here at Zero To Mastery, we have a private Discord community with over 480,000 tech professionals:


You can ask me questions directly, or chat with other students and working professionals. Everyone is super helpful and friendly - regardless of your current skill level.

#8. Python is used everywhere

Python's immense popularity in the programming world makes it an ideal choice for automation tasks, especially in collaborative or long-term projects.

This is because when you write automation scripts in Python, you're using a language that countless other developers are familiar with. This becomes crucial when your scripts need to be maintained or modified by others in the future.

#9. Python is a great entry point into a coding career

Remember how I said we recommend Python to beginners? This is because it’s used in so many industries, such as Machine Learning, AI, Data Science, and more.

If you pick it up now for scripting and automating your tasks, there’s no reason you couldn’t go even further and get a $100k+ a year job in the tech industry.

Examples of Python automation scripts in action

If you’re still not sure if this could help you, let’s look at a few more examples of potential python automations in real-life.

Maybe you’ll have an aha moment and suddenly realize you could streamline a lot of your own tasks.

Sidenote: If you use any of the code examples below, just be aware that you will need to customize them for your own tasks, so that you refer to the correct file names etc.

Example 1: Reading and writing files

If your job involves handling large amounts of data, such as compiling reports or managing lists, automating file reading and writing can save you a lot of time.

For example

A marketing coordinator might need to compile weekly performance reports from multiple CSV files. Automating this task can save them several hours each week, reducing manual errors and ensuring timely updates.

How it works:

# read_write_files.py

with open('input_file.txt', 'r') as file:
	data = file.read()

with open('output_file.txt', 'w') as file:
	file.write(data)

This script reads data from input_file.txt and writes it to output_file.txt. You would need to customize the script with your actual file names and paths, but you get the idea.

Example 2: Sending automated emails

If your job involves sending regular updates or reports via email, automating this process can save you time.

For example

An office manager might need to send daily updates to their team but doesn’t have any kind of automated email software that works internally to help with this.

And so by automating this task, it ensures timely delivery and frees up your time for other tasks.

How it works:

# send_email.py

import smtplib
from email.message import EmailMessage

email = EmailMessage()
email['from'] = 'Your Name'
email['to'] = 'example@example.com'
email['subject'] = 'Daily Update'

email.set_content('This is an automated email with the daily update.')

with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
	smtp.ehlo()
	smtp.starttls()
	smtp.login('your_email@gmail.com', 'your_password')
	smtp.send_message(email)
	print('Email sent successfully')

You would need to customize the email addresses, subject, and content for your specific needs, but again, you can see how simple this could be.

Heck, you could even write a 2nd script to pull all the information that you want to put into the email, saving you additional time!

Example 3: Scraping web data

If your job involves gathering data from the web, such as monitoring competitor prices or tracking news articles, web scraping can save you a significant amount of time.

For example

A PR manager might need to keep track of the latest news about their company.

How it works:

# web_scraping.py

import requests
from bs4 import BeautifulSoup

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

for headline in soup.find_all('h2'):
	print(headline.text)

This script fetches the HTML content from a website and prints out all the headlines. You would need to customize the URL and the specific tags you want to scrape.

You could even set it up to open up specific search terms such as your brand name + news + x time frame. Just in case anything happens.

(PR tools that do this are incredibly expensive. You could even set up the automation to run every 5 minutes and only tell you if something changed since the initial run when you start the day).

Example 4: Tracking keyword positions

Speaking of saving money on tools. If your job involves SEO, tracking your company's position in search engine results for specific keywords can be time-consuming and costly.

By automating this process, you can save on specific tools and provide timely updates.

For example

An SEO specialist might need to monitor keyword rankings daily.

How it works:

# keyword_tracking.py

import requests
from bs4 import BeautifulSoup

keywords = ['your keyword 1', 'your keyword 2']
search_engine_url = 'https://www.google.com/search?q='

for keyword in keywords:
	response = requests.get(search_engine_url + keyword)
	soup = BeautifulSoup(response.text, 'html.parser')
	result = soup.find('h3')
	print(f'Keyword: {keyword}, Top result: {result.text}')

This script searches for specific keywords on Google and prints the top result.

Again, you would need to customize the keywords and possibly the parsing logic based on the HTML structure so that it's looking for your specific keywords, but can you see how much time this would save?

You could even adjust it to only search for those keywords in relation to your rankings, and then have it fill out a CSV file (spreadsheet) so that you can monitor each day over time, completely for free.

TL;DR

As you can see, automations can be used in so many areas. For anything you’re doing more than once per week, you should look at systemizing, building a process, and ideally automating.

It gets a little more complicated as you build more custom automations, but nothing you can’t pick up with a little help and some practice.

To give you an idea of this, let’s walk you through a basic example.

How to get started with basic automations in Python

Before you create any automation, it’s a good idea to learn the basics of Python syntax, such as loops, conditional statements, and how to use libraries.

I cover all of this in my course, but you can also check out the video below for the first 8 hours of our complete Python Developer course!


Don’t feel like you need to know everything though. Get the basics then learn more as you build and figure out what went wrong.

Once you’ve done that, the process is just 4 simple steps.

  1. Install Python: Ensure Python is installed on your computer. You can download it from the official Python website. You only need to do this once
  2. Install an ‘Integrated Development Environment’ (IDE): An IDE, such as VS Code or PyCharm, provides tools and functionalities that make coding easier. They are free tools where you write your code and then help you check it for any issues as you write. Likewise, you only need to do this once
  3. Write your automation
  4. And then run it and see how it works

Obviously, the writing of the code section is the most involved part. However, we can make this simpler by using a GUI.

What is a GUI?

A GUI (Graphical User Interface) tool like PyAutoGUI makes creating Python automation scripts even easier. Basically, it can record the actions you do on the screen with your mouse and keyboard, and then write code to mimic those actions.

For example

You perform a task such as opening a web browser and searching for your company's latest news. The GUI tool watches, writes the code to copy what you just did, and then redoes that task when you run the script in the future.

  • User opens Google Chrome
  • User clicks on the search bar
  • Enters search term for company name + news
  • Changes time frame to past hour
  • If there is a mention, send email alerts to users' mobile device. If not, repeat again in an hour

Easy right? Using a GUI tool simplifies the automation process, especially for tasks that involve multiple mouse clicks and keystrokes. This then means that you don't need to be an expert in Python to create useful automation scripts.

Even better still, recording your actions is faster than writing code manually, and the tool captures exact mouse movements and keystrokes, reducing the chance of errors.

So let’s walk through how to do this.

How to use a GUI tool to automate a task with PyAutoGUI

It's actually very simple.

Step 1: Install PyAutoGUI and PyGetWindow

First, you need to install PyAutoGUI and PyGetWindow. Open your command line or terminal and run:

pip install pyautogui pygetwindow

Step 2: Record the task

We'll use PyAutoGUI along with a simple script to record your actions. This will involve creating a script that captures mouse and keyboard events.

Step 3: Create a recording script

Create a new Python file, for example, record_actions.py, and write the following script to capture your actions:

import pyautogui
import pygetwindow as gw
import time

# Function to record actions
def record_actions(duration=30):
	actions = []
	start_time = time.time()
	print("Recording...")

	while time.time() - start_time < duration:
    	x, y = pyautogui.position()
    	actions.append((time.time() - start_time, x, y))
    	time.sleep(0.1)

	return actions

# Save recorded actions to a file
def save_actions(filename, actions):
	with open(filename, 'w') as f:
    	for action in actions:
        	f.write(f"{action[0]},{action[1]},{action[2]}\n")

# Main function
if __name__ == "__main__":
	duration = int(input("Enter recording duration (seconds): "))
	actions = record_actions(duration)
	save_actions("recorded_actions.txt", actions)
	print("Recording saved to recorded_actions.txt")

Step 4: Run the recording script

Run the script from your IDE or command line. This will start recording your mouse movements and clicks for the specified duration.

python record_actions.py

This script records the mouse position every 0.1 seconds for a specified duration. It also saves the recorded actions (time, x, y coordinates) to a file.

Step 5: Replay the recorded actions

Create another Python file, for example, replay_actions.py, and write the following script to replay the recorded actions:

import pyautogui
import time

# Function to load recorded actions from a file
def load_actions(filename):
	actions = []
	with open(filename, 'r') as f:
    	for line in f:
        	t, x, y = line.strip().split(',')
        	actions.append((float(t), int(x), int(y)))
	return actions

# Function to replay actions
def replay_actions(actions):
	start_time = time.time()
	for action in actions:
    	while time.time() - start_time < action[0]:
        	time.sleep(0.01)
    	pyautogui.moveTo(action[1], action[2])

# Main function
if __name__ == "__main__":
	actions = load_actions("recorded_actions.txt")
	print("Replaying actions...")
	replay_actions(actions)
	print("Actions replayed successfully")

Step 6: Run the replay script

Run the replay script to see the recorded actions being replayed on your screen:

python replay_actions.py

This script loads the recorded actions from the file, and then it replays the actions by moving the mouse to the recorded positions at the recorded times.

Easy!

And just like that, our code is now done.

Now obviously, this is an incredibly basic option. We could do far more complex automations with a little time and patience.

For example

Let's say you have a monthly report for web traffic, and you use 3 sources for this:

  • Google Search Console
  • Google Analytics GA4, and
  • Ahrefs SEO tools

We could get the tool to go to each of these tools, monitor the settings we use for each section of our report spreadsheet, see where we pull the data from, and fill out as many rows as needed - saving hours and completing in just a few minutes - all while we wait.

We would have to do a few security things to make sure passwords could be accessed etc, but the possibilities are endless.

Troubleshooting common issues in Python automation

Not everything will run smoothly the first time, and this is totally fine.

Remember that encountering errors is a natural part of programming, and troubleshooting errors in a calm, measured manner is key. Don’t be discouraged by occasional roadblocks either; errors are how you know you’re doing real programming!

Only by making mistakes can you learn lessons. With that in mind though, here are 4 common issues that often come up, and how to solve them.

Common Issue #1: Your automation script works perfectly on one computer but fails on another

There can be a few reasons for this.

First of all, ensure the script file itself is actually on the machine you want to run it on. A script written on your home PC isn’t automatically accessible on your work computer. You need to copy the script file to each computer where you want to use it.

If you’ve done that and it still doesn’t work, then the issue is usually:

  • Because of differences in the operating system i.e it was written on a PC and your code references windows specific commands, but you're trying to use it on a Mac
  • Or you’ve tweaked the code for the different machines, but the versions of Python and libraries installed on different machines are not the same

For example, a library that works on your Windows machine might not work the same way on a Mac.

So what's the solution?

We can get around all of this by creating a virtual environment to run your scripts on. A virtual environment is an isolated setup that includes the specific versions of Python and libraries your script needs.

How to create a Virtual Environment:

First off, make sure to install virtualenv on your machine.

pip install virtualenv

Then, navigate to your project directory and create a virtual environment:

virtualenv myenv

Next, you need to activate the virtual environment, for your particular machine.

For Windows:

myenv\Scripts\activate

For MacOS or Linux:

source myenv/bin/activate

Finally, you just need to install the required libraries in the virtual environment:

pip install requests

Now your script will run on any machine, and you can access it from the same virtual environment each time.

Common Issue #2: Script runs but doesn't complete the task, and you don't see any error messages

This typically indicates that exceptions (errors) are not being properly handled in your script, causing it to stop running instead of looking for a solution.

To address this, you can use 2 techniques:

  • try-except blocks to catch and handle errors, and
  • Implement logging to see where the issue occurred.

For example

import logging

logging.basicConfig(filename='script.log', level=logging.INFO)
try:
	# Code that might raise an exception
	download_file(url)
except NetworkError as e:
	logging.error(f"Network error: {e}")
	retry_download(url)
except Exception as e:
	logging.error(f"An unexpected error occurred: {e}")
	print("An error occurred: ", e)

So what’s happening here?

By implementing logging, you can check script.log to see the last action the script performed and identify where the issue occurred.

Logging essentially allows the code to tell you what point it is at during the process, helping you pinpoint the exact problem and making debugging much easier.

That’s not the only thing happening though.

The try block contains the code that might cause an error, while the except blocks catch and handle specific errors.

So in this example, if a NetworkError occurs, it logs the error and retries the download. If any other unexpected error occurs, it logs the error and prints a message to the console.

This approach ensures that the script can manage errors without abruptly stopping and provides valuable information for debugging.

Common Issue #3: Including sensitive information by accident

It's easy to include sensitive data directly in your script for convenience, but this practice is risky for security reasons.

So, instead of hardcoding sensitive information, use environment variables or secure files that your script can read when necessary. This practice protects your sensitive information from being exposed in your codebase.

import os

email_password = os.getenv('EMAIL_PASSWORD')

This way, your sensitive information is stored securely outside of your codebase, reducing the risk of it being exposed in version control systems or shared inadvertently.

Common Issue #4: Script takes longer to complete the task than it would take to do it manually

This may happen because your script is not optimized or could be making unnecessary calls to an API or database.

The best thing to do here is to review your script to ensure it's efficient and not repeating tasks unnecessarily, or even adding in unnecessary timing issues.

For example

If your script processes files, make sure it only processes each file once. The reason for this is that although you might want your pc to do 10 tasks, it's often faster to do 1 task 10 times, vs doing 10 tasks all at once.

Same output at the end, but dramatically different time to get it completed. No joke, this can significantly improve the efficiency of your script.

processed_files = set()
for filename in os.listdir(directory):
	if filename not in processed_files:
    	process_file(filename)
    	processed_files.add(filename)

You could also further optimize your code by reducing redundant operations and using efficient algorithms.

Now it's your turn to start automating

Hopefully this guide has opened your mind to the possibilities of Python automation scripts, and how you can use them to simplify your own life.

Python automation can be an incredible tool, enhancing your productivity by handling repetitive tasks and reducing the chance of errors.

Even if you're a complete beginner, Python's simple syntax and readability make learning it a manageable task. Before you know it, you'll have your own set of digital assistants making your life easier!

Automation is not just for coders. With the right guidance and tools, anyone can start automating their tasks to save time and increase efficiency. Imagine all the time you spend on repetitive tasks each day, and think about how much more productive you could be if you could automate even a portion of those tasks.

By following the steps and tips outlined in this guide, you should be well on your way to becoming proficient in Python automation.

P.S.

However, if you want to take your skills to the next level and learn more advanced techniques, definitely check out my Python automation course.

learn python automation

This course will turn you into an automation wizard that can automate away all the boring, annoying parts of your work and life. You'll learn by being hands-on and building 11 automation projects using Python and AI. All from scratch. No coding experience is required.

And don’t forget, you’ll also have access to me for any questions, in the private Discord community.

What do you have to lose? And how much of your time could you save by learning this?

I think you might be surprised just how much easier you can make your job if you work smarter, not harder. You can do this. No coding experience required.

More from Zero To Mastery

How To Become A Web Developer (From Complete Beginner to Hired) preview
How To Become A Web Developer (From Complete Beginner to Hired)

Want to become a Web Developer but not sure how? Our step-by-step guide shows you how to go from beginner to hired (without wasting $1,000s on a bootcamp or degree). And we answer all your FAQ.

Starting Over At 56: A Journey From Consulting To Coding preview
Starting Over At 56: A Journey From Consulting To Coding

Discover how one ZTM student switched from consulting to coding, navigating the challenges of a late-career change - to achieve success in web development.

What’s The Best Way To Learn To Code? preview
Popular
What’s The Best Way To Learn To Code?

Coding Bootcamp vs Degree vs Self-Taught? There are pros & cons of each route. This deep dive breaks it all down and will help you find the best option for YOU.