Importing modules from parent folder
In Python, you can use the sys.path.append() method to add the parent directory to the list of paths where Python looks for modules.
In Python, you can use the sys.path.append() method to add the parent directory to the list of paths where Python looks for modules. Here is an example:
Using sys.path.append method in Python to add the parent directory to the list of paths where Python looks for modules
import sys
import os
# Add parent directory relative to the current script's location
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# Now you can import modules from the parent directory
import my_module
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can use the PYTHONPATH environment variable to include the parent directory in the Python module search path.
Using PYTHONPATH environment variable to include the parent directory in the Python module search path
# in the command shell
export PYTHONPATH=..:$PYTHONPATH
# in windows command shell
set PYTHONPATH=..;%PYTHONPATH%Please be aware that adding a directory to sys.path will make all modules in that directory importable, not just the one you want to use. The standard Pythonic approach for packages is to use relative imports:
from .. import my_moduleAnother method is using importlib.util.find_spec(), but it is more advanced and not recommended for general use.