Import modules from a neighboring folder in Python

I posed the question in the figure below:

enter image description here

EDIT The question posed next to the figure is as follows:

How to get script_A1 to import a function from script_B2?

Similar questions were asked before. But most answers suggest adding the / script / package module (independently) to the PATH variable. For instance:

sys.path.append('...')

But adding a module to the PATH variable just seems wrong. I do not want to change my system in any way. When my application closes, I want my Python environment to be clean and untouched. I am afraid that adding uncontrolled modules to PATH variables on my system will cause headaches later.

Thank you for helping me :-)

+4
3

:

import sys
sys.path.append('..')
import folderB.something

imp.load_source, .

+2

_A1;

from folderB.script_B2 import YourClass as your_class

0

, .

PATH. script_A1:

import sys
import os
myDir = os.path.dirname(os.path.abspath(__file__))
parentDir = os.path.split(myDir)[0]
if(sys.path.__contains__(parentDir)):
    print('parent already in path')
    pass
else:
    print('parent directory added')
    sys.path.append(parentDir)

# Now comes the rest of your script

, myProject PATH, :

    print(sys.path)

myProject PATH, /modules/any . script_B2 folder_B:

import folder_B.script_B2 as script_B2

, ​​ Python . PATH , , .

0

All Articles