Home > database >  Importing a class from another directory
Importing a class from another directory

Time:09-27

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.

CodePudding user response:

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)

CodePudding user response:

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
  • Related