Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

please read my problem:

I am trying to import a class from a file from a subdirectory

> main.py > --->folder/ > ----->file.py

and in file.py I have a class implemented ( Klasa) What have I tried:

putting in main.py:

from folder import file 

from file import Klasa

I am getting the error:

from file import Klasa

ImportError: No module named 'file'

When I try to use just:

from folder import file

I get this error:

tmp = Klasa()

NameError: name 'Klasa' is not defined

I have put an empty __init__.py in the subfolder and it still does not work, and I have put in the __init__.py : from file import Klasa and still doesnt work.

If main and file are in the same folder this work:

from file import Klasa

but I want them to be in separate files.

Can someone tell me what I am doing wrong?

1 Answer

0 votes
by (106k points)

The error you are getting because you have not specified the right path to the file. You can try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file

k = file.Klasa()

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
+3 votes
2 answers

Browse Categories

...