OneManArmy
OneManArmy

Reputation: 43

Importing a class from another directory

I know this question has been asked before but none of the solutions worked for me. So let's say I have a directory structured as follow :

folder1:
 -- file1.py
folder2:
 -- class2.py

I want to call the class from class2.py in my file1.py so what I did at the start of the file1.py is

from folder2.class2 import Class2

But the following issue arises:

ModuleNotFoundError: No module named 'folder2'

so I tried something else:

from .folder2.class2 import Class2

the following issue arises:

ImportError: attempted relative import with no known parent package

I read a solution on the site where you add __init.py__ in the folder2 but it didn't help.

Any suggestions please? Thank you.

Upvotes: 1

Views: 127

Answers (2)

Mouxiao Huang
Mouxiao Huang

Reputation: 1

folder1:
-- __init__.py
-- file1.py
folder2:
-- __init__.py
-- class2.py

in class2.py:

class Class2():
    def __init__(self):
        pass
    ...

in file1.py:

import sys
sys.append('..')
from folder2.class2 import Class2

Upvotes: 0

Red
Red

Reputation: 27557

You can insert any path into your sys via the sys.path.insert method:

import sys
path = '\\'.join(__file__.split("\\")[:-2])
sys.path.insert(1, path)

from folder2.class2 import Class2

In the above code I made it so that the directory holding folders folder1 and folder2 gets inserted into the system. If the location of the directories is fixed, a more clear way would be to directly use the path of the folder:

path = 'C:\\Users\\User\\Desktop'
sys.path.insert(1, path)

Upvotes: 1

Related Questions