bsky
bsky

Reputation: 20222

ImportError: No module named even after I appended to system path

I have the following files:

./ElementExtractor.py
./test/ElementExtractorTest.py

In ElementExtractorTest.py, I am trying to import ElementExtractor.py like this:

import sys
sys.path.append('../')
import ElementExtractor

However, I am getting:

ImportError: No module named 'ElementExtractor'

How come it's not seen?

Is there a simple way to import another class with a relative reference?

Upvotes: 2

Views: 2770

Answers (2)

Wojciech Walczak
Wojciech Walczak

Reputation: 3599

The general answer to this question should be don't, I guess. Messing with relative paths means that the path is relative to the place from where you're calling it. That's why PYTHONPATH is worth embracing instead.

Let's assume, your directory structure looks like this:

./projects/myproject/ElementExtractor.py
./projects/myproject/test/ElementExtractorTest.py

Now, you're calling your script like this:

[./projects/myproject]$ python3.5 ./test/ElementExtractorTest.py

Your current directory is myproject and in ElementExtractorTest.py you're adding ../ directory to sys.path. This means, that ./projects/myproject/../ (i.e.: ./projects) is effectively added to your PYTHONPATH. That' why Python is unable to locate your module.

Your code would work from test directory though:

[./projects/myproject/test]$ python3.5 ./ElementExtractorTest.py

Now, by adding .. to sys.path you are effectively adding ./projects/myproject/test/../ (i.e. ./projects/myproject) to sys.path, so the module can be found and imported.

Upvotes: 3

Shiva Kishore
Shiva Kishore

Reputation: 1701

my folder structure

 ./test.py
 ./Data.py

from test.py

import Data
obj = Data.Myclass()

update

in your case

from ..ElementExtractor import MyClass

Hope this helps :)

Upvotes: -2

Related Questions