简体   繁体   English

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

[英]How to import a file from the same directory in python?

I have the following directory structure in python. 我在python中具有以下目录结构。

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

In mel2samp.py I want to import TacotronSTFT from tacatron2.layers using these lines of code 在mel2samp.py中,我想使用以下代码行从tacatron2.layers导入TacotronSTFT

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

But it throws an error ImportError: No module named tacotron2.layers . 但这会引发错误ImportError: No module named tacotron2.layers

Also need an empty __init__.py file in tacotron2 folder. tacotron2文件夹中还需要一个空的__init__.py文件。 After that you can do: 之后,您可以执行以下操作:

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

But it is recommended to make tacotron2 as a package by adding init.py 但是建议通过添加init.py使tacotron2成为软件包。

Then you can use it as 然后您可以将其用作

from tacotron2.layers import TacotronSTFT #Use TacotronSTFT

You can make your folder a package by adding __init__.py 您可以通过添加__init__.py将文件夹打包
You can read more about it here 您可以在这里了解更多信息

The __init__.py files are required to make Python treat the directories as containing packages; __init__.py文件是使Python将目录视为包含包所必需的; 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. 这样做是为了防止具有通用名称的目录(例如string )无意间隐藏了稍后在模块搜索路径上(更深层)出现的有效模块。 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. 在最简单的情况下, __init__.py可以只是一个空文件,但它也可以为该程序包执行初始化代码或设置__all__变量,如后所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM