1

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.

1
  • 1. Make sure the root directory (the one that contains folder1 and folder2) is on your PYTHONPATH. 2. Make sure folder1 and folder2 each contain an __init__.py. Commented Sep 27, 2021 at 13:06

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

thank you but this didn't work either still got the ModuleNotFoundError
@OneManArmy With the first code or the second code in my answer?
with the first code, I didnt try the second because I will dockerize the application therefore I dont think it's a good idea to use C:\\Users\\...
@OneManArmy Try replacing the \\` with /` then.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.