简体   繁体   中英

Importing a file from a Python package in to a directory

I'm building a Python package and came across this situation. Here's the project structure :

my-package/
      examples/
           example.py
      my-package/
           __init__.py
           basic.py
           main.py

From the above project structure we can see that my-package is a package while examples is just a directory. Here what would be the best way to import basic.py in example.py .

from my-package import basic in example.py would throw No module named ... .

您可以做的一件事是在my-package下添加一个__init__.py文件,以便my-package成为包目录,以便可以将其中的模块导入到该文件中。

can you try creating an __init__.py under the main directory, and let me know about the results?

__init__.py :

import my-package.basic as basic

example.py :

from .. import basic

the final directory structure should be like:

my-package/
      __init__.py
      examples/
           example.py
      my-package/
           __init__.py
           basic.py
           main.py

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