如何在python中从同一目录导入文件?

2024-06-07 03:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有以下目录结构。你知道吗

├── mel2samp.py
├── tacotron2
│   ├── layers.py

在mel2中山梨我想使用这些代码行从tacatron2.layers导入TacotronSTFT

import sys
sys.path.insert(0, 'tacotron2')
from tacotron2.layers import TacotronSTFT

但它抛出了一个错误 ImportError: No module named tacotron2.layers。你知道吗


Tags: path代码frompyimport目录layerssys
3条回答

您可以通过添加__init__.py
你可以阅读更多关于它here

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

import sys
sys.path.insert(0, 'tacotron2')
from tacotron2.layers import TacotronSTFT
# Use TacotronSTFT

但建议通过添加初始.py你知道吗

然后你就可以用它来

from tacotron2.layers import TacotronSTFT #Use TacotronSTFT

tacotron2文件夹中还需要一个空的__init__.py文件。之后你可以做:

import sys
from tacotron2.layers import TacotronSTFT

相关问题 更多 >