Hello! Welcome to the final lesson of our first module, "Python Foundations for Automation."
In our last lesson, you learned how to define and call your own functions. This gave you the power to create reusable blocks of code, making your scripts organized and efficient. You now know how to build your own tools.
But what if the tool you need already exists? Today, we will learn how to import and use modules from the Python Standard Library. This will unlock a huge collection of pre-written, professional code that can do everything from generating random numbers to interacting with your computer's files. Mastering this will dramatically speed up your ability to write powerful automation scripts.
1. What are Modules?
Think of a module as a code library. It's simply a Python file (.py) that contains a set of functions, variables, or classes that you can include in your application.
Imagine you are managing inventory. You could write functions for check_stock(), generate_order_id(), and calculate_vat() and save them all in a single file called inventory_tools.py. Then, in your main script, you could simply import inventory_tools and use those functions without having to write them again. This keeps your main script clean and your tools organized.
The W3Schools page on Python Modules gives a very clear and simple definition of what a module is and how to use it. It's a great starting point.
Read the sections 'What is a Module?', 'Create a Module', and 'Use a Module'. This will show you the basic idea of saving code in one file and using it in another.
2. How to Import Modules
There are a few common ways to import modules into your script. Each has its use case.
Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library
Corey Schafer's tutorial on importing modules provides excellent, clear examples of the different import methods. We will watch a few short clips to cover the main syntaxes.
Please watch from the beginning until 06:11. Pay close attention to the following syntaxes: import module (00:00 - 01:58): How to import an entire module and call a function using module_name.function_name(). import module as alias (01:58 - 03:36): How to give a module a shorter nickname (an 'alias'), like import my_module as mm. from module import item (03:36 - 05:09): How to import just a specific function or variable from a module, so you don't need to use the module's name. from module import * (05:09 - 06:11): Understand why this method is generally discouraged as it can make code confusing.
To summarize the key methods:
import math: Imports the whole module. You access its contents withmath.pi. This is clear and avoids naming conflicts.import math as m: Imports the whole module but gives it a shorter name. You access contents withm.pi.from math import pi: Imports only thepivariable. You can usepidirectly. This is useful for a few specific items.
3. Exploring the Python Standard Library
One of the best things about Python is that it comes with a huge collection of ready-to-use modules called the Python Standard Library. You don't need to install anything extra to use them. They provide powerful tools for common tasks.
Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library
Let's continue with Corey Schafer's video to see what the Standard Library is and look at a few examples.
Watch from 13:33 to 17:59. This section introduces the Standard Library and gives you a taste of some useful modules like: random: For generating random numbers or making random choices. math: For advanced mathematical operations. datetime: For working with dates and times. os: For interacting with the operating system (like files and folders).
A very useful tool for exploring a new module is the built-in dir() function. It lists all the functions and variables available inside a module.
import random
# See everything inside the 'random' module
print(dir(random))
Test your understanding!
Your task is to create a script that randomly assigns a task to a team member.
- Create a list of team members:
["Alice", "Bob", "Charlie", "David"]. - Import the
randommodule. - Use a function from the
randommodule to select one name from the list. - Print a message like:
"The next task is assigned to: [Selected Name]".
Hint: The video mentioned random.choice().
Show answer
import random
team_members = ["Alice", "Bob", "Charlie", "David"]
# Use random.choice() to select one item from the list
assigned_person = random.choice(team_members)
print(f"The next task is assigned to: {assigned_person}")
4. A Practical Example: The os Module
For automation, one of the most important modules in the standard library is os. It lets your Python scripts interact with the operating system, allowing you to manage files and directories. This is fundamental for tasks like organizing downloads, processing log files, or managing project assets.

Let's look at a few of the most useful functions from the os module.
Python Tutorial: OS Module - Use Underlying Operating System Functionality
Corey Schafer has a detailed video on the os module. We will watch specific clips that cover the functions most critical for starting with automation.
Watch the following three short segments: Get/Change Directory (01:08 - 02:10): Learn about os.getcwd() to find out which folder your script is running in and os.chdir() to change to a different folder. List Contents (02:10 - 02:44): Learn how to use os.listdir() to get a list of all files and folders in a directory. Build Paths Safely (12:26 - 14:15): This is very important! Learn why you should always use os.path.join() to combine folder and file names into a path, instead of just adding strings with +.
Using os.path.join() is a critical best practice. It automatically uses the correct path separator (/ on macOS/Linux, \ on Windows), preventing common bugs when your script runs on different computers.
Let's combine these into a simple script:
import os
# 1. Get the current working directory (where the script is running)
current_directory = os.getcwd()
print(f"Current folder: {current_directory}\n")
# 2. List all files and folders in that directory
contents = os.listdir(current_directory)
print(f"Contents of the folder: {contents}\n")
# 3. Create a safe path to the first item in the list
if contents: # Check if the list is not empty
first_item_name = contents[0]
full_path = os.path.join(current_directory, first_item_name)
print(f"Full path to the first item: {full_path}")
Test your understanding!
Write a script that lists all the files and folders on your Desktop.
- Import the
osmodule. - Get your home directory path using
os.environ.get('HOME')(for Mac/Linux) oros.environ.get('USERPROFILE')(for Windows). A more universal way for now is to get your home path and join it with 'Desktop'. Let's find your home path first. - Use
os.path.join()to create the full path to your Desktop folder. - Use
os.listdir()to get the contents of the Desktop. - Print the list of contents.
Note: The exact home directory logic can be tricky. For this exercise, you can hardcode the path to your Desktop if needed, but try to use the environment variable method first! For example, on Windows, it might look like os.path.join(os.environ.get('USERPROFILE'), 'Desktop').
Show answer
import os
# This solution tries to be cross-platform.
# Get the user's home directory
home_directory = os.environ.get('HOME') or os.environ.get('USERPROFILE')
if home_directory:
# Create the path to the Desktop
desktop_path = os.path.join(home_directory, 'Desktop')
# Check if the Desktop path actually exists before listing it
if os.path.exists(desktop_path):
print(f"Looking inside: {desktop_path}\n")
# Get the list of files and folders
desktop_contents = os.listdir(desktop_path)
print("Files and folders on your Desktop:")
# Print each item on a new line for better readability
for item in desktop_contents:
print(f"- {item}")
else:
print(f"Error: Could not find the Desktop folder at {desktop_path}")
else:
print("Error: Could not determine the home directory.")
Conclusion
Congratulations on completing the first module! You've built a solid foundation in Python, from variables and loops to functions and modules.
Key Takeaways:
- Modules are reusable Python files (
.py) containing functions and variables. - The
importstatement is used to bring modules into your script. Key syntaxes includeimport module,import module as alias, andfrom module import item. - The Python Standard Library is a rich collection of built-in modules that you can use without any extra installation.
- The
osmodule is a powerful tool for automation, allowing you to interact with your computer's file system. - Always use
os.path.join()to create file paths for reliability.
Next Lesson:
You are now ready to start building real automation scripts. In our next lesson, we will kick off Module 2: Automating Local Tasks with Python. We will dive deeper into file system automation by learning how to read data from and write data to text files, a fundamental skill for almost any automation project.