Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python从另一个文件夹导入类';s文件_Python_Python 3.x_Import - Fatal编程技术网

python从另一个文件夹导入类';s文件

python从另一个文件夹导入类';s文件,python,python-3.x,import,Python,Python 3.x,Import,我使用的是Python3,我的文件夹结构如下 Main_Folder > Export > >exportmanager.py > Examples > >test.py exportmanager.py文件有一个类exportmanager,我需要在test.py中导入它。 到目前为止我已经试过了 from Export.exportmanager import ExportManager from Main_Folder.Export import

我使用的是Python3,我的文件夹结构如下

Main_Folder
> Export
> >exportmanager.py

> Examples
>  >test.py
exportmanager.py文件有一个类exportmanager,我需要在test.py中导入它。 到目前为止我已经试过了

from Export.exportmanager import ExportManager
from Main_Folder.Export import exportmanager.py then from exportmanager.py import ExportManager
还有其他一些。
但我一直找不到模块。

我想到的唯一快速、肮脏的解决方案是采用以下结构:

.
├── Examples
│   ├── __init__.py
│   └── test.py
├── Main_Folder
│   ├── Export
│   │   └── exportmanager.py
│   └── __init__.py
├── __init__.py
假设您的exportmanager.py如下所示:

def fun():
    print("This is from Export Manager!")
def fun():
打印(“这是来自导出管理器!”)
然后在test.py中使用以下方法导入此项:

导入操作系统
导入系统
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(_文件__)))
从主文件夹导出导出管理器
exportmanager.fun()
我尝试使用相对导入,其他“最简单”的解决方案,所有这些解决方案都给出了相同的错误“ImportError:在没有已知父包的情况下尝试相对导入”。 因此,如果你正在寻找一个肮脏的解决办法,这可能是它。至于为什么会有一些init.py文件,这些文件在本例中基本上是空的,我鼓励您更多地阅读(即)


玩得开心。

假设您的exportmanager.py如下所示:

def fun():
    print("This is from Export Manager!")
您可以在test.py中编写以下代码:

from pathlib import Path
from sys import path
path.append(str(Path(__file__).parents[1] /Path('Main/Export')))

import exportmanger

exportmanger.fun()

我尝试使用Przemysław Samsel的答案,但它会产生一个modulenofound错误

看一看,我想这是另一个例子,我真的不明白部门“/”在那里做什么。我的代码所做的只是将父目录附加到Python的路径。然后,如果您像我指出的那样创建了所有这些init.py文件,那么Python在查找exportmanager时应该没有问题。不管怎样,让我们看看OP怎么说“/”在目录树中移动。我的答案是将Main_文件夹/Export目录附加到Python的路径