Import from a custom folder

Mediumsys Module Programs · 10 of 20

Write a Python program that adds a folder to sys.path and imports a module from it.

Advertisement
Output
Hello, SQA Tools!

Approach

  1. Append the folder, then import.

Solution

Python
import osimport sys os.makedirs("my_libs", exist_ok=True)with open(os.path.join("my_libs", "greetings.py"), "w") as f:    f.write("def hello(name):\n    return f'Hello, {name}!'\n") sys.path.append(os.path.abspath("my_libs"))import greetings print(greetings.hello("SQA Tools"))
Output
Hello, SQA Tools!
Tip

For real projects, install your package (pip install -e .) instead of changing sys.path.

Learn the concept

New to this topic? Read the lesson, then come back.

More sys module programs

← All 20 sys Module Programs

Leave a Comment