Resources
Lesson Objectives
How to Use Packages in Python
Examples of Built-In Packages:
os
sys
datetime
time
math
random
Are you Ready?
Summary
Important Definitions
It's time to talk about Packages and Modules in python.
There are thousands of packages available for anything you can imagine, so you can save a lot of time by using packages created by other developers. They are all open-source and free to use. Isn't it amazing?
Package – A collection of modules organized in a folder structure, usually with an __init__.py
file to indicate it's a package.
Module – A single Python file containing reusable functions, classes, or variables that you can import into your script.
When importing packages or modules, the syntax looks the same.
Basic Syntax: How to import packages and modules?
When you want to use code from packages or modules, you need to import them into your own script by using import
keyword followed by the package name.
For Example:
As I've already mentioned Package is a folder that contains Modules (python files) within a folder structure. But you use them the same way.
For example imagine this:
📂 Package
——📂 subfolder_a
———— 📂 subfolder_b
——————module.py (contains reusable ef_function
)
When you import in Python, you can use dots .
to go deeper into folder structure until you find what you need. Usually python auto-complete or AI chat bots will help you navigate known packages.
Let's say that we want to import the function from this package to use in our code. Let's look into multiple examples we could do that.
Firstly, we could import Package and then reference function from inside of it like this:
We could also import only the function, so we don't have to follow this long path every time. This time we would also need to use
from
keyword.
We could also import one of the subfolder or module in case we would want to use more than one function inside of it.
All these examples would give you the same result that simply uses ef_function()
, but you can decide how you import it so you can reuse it.
💡Just remember: Each dot (.
) lets you go deeper into the folder structure, like navigating files!
Also, to import any package or module in your script it has to be downloaded and referenced by your python interpreter.
Usually you would create a virtual environment for your project (a box) where you can install packages that you will need to use in that project. And then you can import them and use in your code.
Quick Note: Download New Packages
For example, if you use pyCharm you can install additional packages by going to:
Settings -> Project -> Python Interpreter.
Then you will see a list of all installed packages, and you can add even more by using + Plus icon, and then searching for a package by name. Once you find your package, check the version and install it if your python version can support it.
If you use other code editors, you might need to use a built-in terminal and write something like pip install package_name
. But we won't need any new packages for this lesson.
Instead, we will look into built-in modules available in python by default. Let's start with an os
module which is used for operating system commands.
Quick Note: Path string in Python
Before we begin with os
module, let me share a tip on storing paths in strings.
Python strings can have special meanings for combination of backslashes \
and certain letters. For example, \n
combination will be read as a New-Line in Python.
For example, you can see that pyCharm will highlight it in the string:
To avoid this unwanted behavior we can place r
in the beginning to mark is as a raw-string. Then all special combinations will be ignored by python.
💡That's a good trick to use on paths in strings
Now, let's continue to os
module.
os
module - Operating System commands
The os
module is your go-to package when you need to interact with the operating system. You will often use it to check if a folder exists, create a new folder, join paths, rename files and similar tasks…
Let me show you a few simple examples you mind need in your scripts.
#️⃣os.path.exists(path) - Check if path exists
#️⃣os.makedirs(path) - Create Folder
Let's continue with previous example, and create a folder only if it doesn't exist to avoid any errors.
#️⃣os.path.join('part_a', 'part_b') - Join parts as a path.
When you want to combine multiple pieces of a path together, it's best to use os.path.join. This way you don't need ot check if your parts end with a slash or not to avoid mistakes.
Here is a simple example:
Let's also combine the previous examples and create multiple paths to create new folders like this:
#️⃣ Rename Files
Now, let's have a look how to rename files with python. Renaming files can be done easily with the os module. You would need 2 functions:
os.listdir(path)
- list all files inside of provided directory (directory means folder)
os.rename(old_path, new_path)
- Rename file
Let's break it down:
We have a path where we have a lot of
png
files.We create a loop for a list of files we get from
listdir
We check if filename has
.png
inside its path.Then we create a new filename by adding a date with the
replace
method.Then we need absolute path with old and new filenames
Rename files
That might look like a lot of steps, but if you go over them, you will realize that it's not so complex.
#️⃣ Explore Nested Folders
The next one is a bit too advanced, but it might come useful in the future.
There is a function os.walk
that can give you a list of all nested sub-folders and files. It can be useful to quickly find certain files or just to navigate inside your folder structure.
Here is a simple example to find a file with 'test'
in its name:
#️⃣ sys.exit() - Stop Code Execution
The next one will stop your script execution immediately. It can be useful when you make a condition and it has failed. It might be better to stop execution before you catch an error.
Here is the code:
#️⃣ Get Date and Time
You will often use this module if you would want to get today's date, or format a date in a specific way.
You can find a table here of all special symbols for time string formatting.
#️⃣ Time Module
There is also a time module.
You might find a use for sleep function that allows you to wait during your code execution.
#️⃣ Math Module
The math module is essential when doing calculations.
Here are just a few examples:
#️⃣ Random Module
Whenever you need to generate a random number or get a random item you would use a random
module. Here is how it works:
HomeWork
Try a few code samples in this lesson to understand how import works. There is no need to learn these modules by heart.
In general, when you will need any of them, you would probably ask ChatGPT or similar AI tool, and get a code snippet with explanation how it works.
Overtime you will get familiar with the modules and functions that you need to use the most. There is no need to rush this process.
⌨️ Happy Coding!