简体   繁体   中英

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

I have the following directory structure in python.

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

In mel2samp.py I want to import TacotronSTFT from tacatron2.layers using these lines of code

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

But it throws an error ImportError: No module named tacotron2.layers .

Also need an empty __init__.py file in tacotron2 folder. 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

Then you can use it as

from tacotron2.layers import TacotronSTFT #Use TacotronSTFT

You can make your folder a package by adding __init__.py
You can read more about it 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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