Skip to content
Advertisement

Cannot Locate my Module from another folder n python

I’ve the following structure in my simple python project:

MainFolder
|
├───authentication
│   └───apikey.py
|   └───tokengenerator.py
├───Functions
│   └───generatedata.py

The tokengenerator.py module produces Token variables and I need to call it in generatedata.pymodule and I used the following code line for this purpose:

from authentication.tokengenerator import Token

but it returns the error below:

Exception has occurred: ModuleNotFoundError
No module named 'authentication'

Would you please advise ?

Advertisement

Answer

from this article, you can add the path below the Functions folder to the searchpath for modules by adding .. (combined with the scriptpath)

import os
import sys

script_dir = os.path.dirname( __file__ )
mymodule_dir = os.path.join( script_dir, '..')
sys.path.append( mymodule_dir )

from authentication.tokengenerator import Token
token = Token()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement