This question already has an answer here:
这个问题在这里已有答案:
- Importing files from different folder 20 answers
导入来自不同文件夹的文件20个答案
Before you mark it as duplicate 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 imlpemented ( Klasa
) What have I tried:
并在file.py我有一个类imlpemented(Klasa)我尝试了什么:
putting in main.py:
放入main.py:
from folder import file
from file import Klasa
I am getting the error:
我收到错误:
from file import Klasa
从文件导入Klasa
ImportError: No module named 'file'
ImportError:没有名为'file'的模块
When I try to use just:
当我尝试使用时:
from folder import file
I get this error:
我收到此错误:
tmp = Klasa()
tmp = Klasa()
NameError: name 'Klasa' is not defined
NameError:未定义名称“Klasa”
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.
我在子文件夹中放了一个空的__init__.py,它仍然无效,我已经放入__init__.py:从文件导入Klasa,但仍然无法正常工作。
If main and file are in the same folder this work:
如果main和file在同一个文件夹中,则可以正常工作:
from file import Klasa
从文件导入Klasa
but i want them to be in separate files.
但我希望他们在单独的文件中。
Can someone tell me what i am doing wrong?
有人能告诉我我做错了什么吗?
1 个解决方案
#1
60
Your problem is basically that you never specified the right path to the file.
您的问题基本上是您从未指定文件的正确路径。
Try instead, from your main script:
请尝试从您的主脚本:
from folder.file import Klasa
Or, with from folder import file
:
或者,使用from folder import file:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
#1
60
Your problem is basically that you never specified the right path to the file.
您的问题基本上是您从未指定文件的正确路径。
Try instead, from your main script:
请尝试从您的主脚本:
from folder.file import Klasa
Or, with from folder import file
:
或者,使用from folder import file:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()