How to import Common.py using relative path in Python?

Great suggestions from both @ishrth_fathima If you’re looking for more control over how you import modules, particularly with dynamic paths or more complex setups, you might want to explore the importlib module. It’s a powerful tool that gives you complete flexibility. Here’s how you can use it for a python import relative path from within your project:

import importlib.util
import os

module_name = 'Common'
module_path = os.path.join(os.path.dirname(__file__), '..', 'Common', 'Common.py')

spec = importlib.util.spec_from_file_location(module_name, module_path)
common_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(common_module)

This method works great when you need to import dynamically from a relative path and gives you fine-tuned control over the import process. It’s especially useful when you’re working with unconventional or constantly changing directory structures. Plus, it helps you avoid issues that might arise with sys.path.append in the long run