wasp256
wasp256

Reputation: 6242

Python3 import module from subfolder2 in subfolder1

I have the following file structure

MainDirectory
    | Subfolder1
        | script1.py
    | Subfolder2
        | __init__.py
        | script2.py

I want to import the the module script2.py in the script1.py. With Python2.7 I was able to do it like this:

The __init__.py contains the code:

 from script2 import ClassA

File script1.py contains the following import structure:

 sys.path.insert(0, "../")
 from SubFolder2 import ClassA

But when I run the same in Python3 then I get an

 ImportError: No module named 'script2'

What would I have to change to get it to work with Python3?

Upvotes: 1

Views: 64

Answers (2)

user7711283
user7711283

Reputation:

This works as expected:

import sys
import os
sys.path.insert(0, '/'.join(os.path.dirname(os.path.abspath(__file__)).split('/')[0:-1])+'/Subfolder2')
import script2

Upvotes: 1

Colin Schoen
Colin Schoen

Reputation: 2592

You need to specify that this resource is in a parent directory...

from ..SubFolder2 import script2

Upvotes: 0

Related Questions