Python-13

/

/

/

python/13-other-libraries

Packages in Python.

Python is amazing because of its community. And there are packages available for anything you could imagine. But in this lesson, let's look at some of built-in packages and see how they can be useful.

Python-13

/

/

/

python/13-other-libraries

Packages in Python.

Python is amazing because of its community. And there are packages available for anything you could imagine. But in this lesson, let's look at some of built-in packages and see how they can be useful.

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:

import os #os is a built-in python module

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.

  1. Firstly, we could import Package and then reference function from inside of it like this:

import Package

x = Package.subfolder_a.subfolder_b.module.ef_function()
  1. 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.

from Package.subfolder_a.subfolder_b.module import ef_function

x = ef_function()
  1. We could also import one of the subfolder or module in case we would want to use more than one function inside of it.

from Package.subfolder_a.subfolder_b import module 

x = module.ef_function()

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.

path = r"C:\Users\Erik\Documents\PythonTest\new Folder"

💡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

import os

# Define the path (using a raw string to avoid special character issues)
path = r"C:\Users\Erik\Documents\PythonTest\New Folder"

# 1️⃣ Check if Folder Exists or create it.
if os.path.exists(path):
    print("Path Exists.")
else:
    print("Path Doesn't 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.

import os

# Define the path (using a raw string to avoid special character issues)
path = r"C:\Users\Erik\Documents\PythonTest\New Folder"

# 1️⃣ Check if Folder Exists or create it.
if os.path.exists(path):
    print("Path Exists.")
else:
    print("Path Doesn't Exists.")
    # Create new Folder
    os.makedirs(path)
    print("Folder created successfully.")

#️⃣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:

import os

path = r"C:\Users\Erik\Documents\PythonTest\New Folder"

new_path = os.path.join(path, 'Subfolder', 'abc')
print(new_path)

Let's also combine the previous examples and create multiple paths to create new folders like this:

import os

path = r"C:\Users\Erik\Documents\PythonTest\New Folder"
list_folder = ['Folder_A', 'Folder_B', 'Folder_C']

for folder in list_folder:
    new_path = os.path.join(path, folder)
    if not os.path.exists(new_path):
        os.makedirs(new_path)
        print('Created Folder: {}'.format(folder))

#️⃣ 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

import os

path = r"C:\Users\Erik\Documents\PythonTest\Items"

for filename in os.listdir(path):
    print(filename)
    if '.png' in filename:
        new_filename = filename.replace('.png', '_250125.png')
        abs_old_filepath = os.path.join(path, filename)
        abs_new_filepath = os.path.join(path, new_filename)
        os.rename(abs_old_filepath, abs_new_filepath)
        print('Renamed File: {} to {}'.format(abs_old_filepath, abs_new_filepath))

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:

import os

path = r"C:\Users\Erik\Documents\PythonTest"

for root, dirs, files in os.walk(path):
    for file in files:
        if 'test' in file:
            # Get Absolute path
            abs_path = os.path.join(root, file)
            print(abs_path)

#️⃣ 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:

import sys

print('Before')
sys.exit()  # Stop script execution
print('After')  # This line will never be executed.

#️⃣ 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.

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
formatted_time = now.strftime("%H:%M:%S")

print(now)
print(formatted_date)
print(formatted_time)

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.

import time

for i in range(50):
    time.sleep(1)
    print('Second has passed.')

#️⃣ Math Module

The math module is essential when doing calculations.

Here are just a few examples:

import math

# Square root of a number
num = 16
root = math.sqrt(num)
print(root)

# Calculate area using Pi
r = 3
area = math.pi * r**2
print(area)

# Ceiling (round up) and Floor (round down)
num = 15.7
ceil_num = math.ceil(num)
floor_num = math.floor(num)
print(ceil_num)
print(floor_num)

#️⃣ 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:

import random

# Random Number Generator for RGB values
R = random.randint(0, 255)
G = random.randint(0, 255)
B = random.randint(0, 255)
print(R, G, B)

import random

# Random Item selector
meterials = ['Wood', 'Glass', 'Brick', 'Concrete']
random_meterial = random.choice(meterials)
print(random_meterial)

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!

Questions:

Should I remember all these modules?

Should I remember all these modules?

Can I create my own package?

Can I create my own package?

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API