首页 > 解决方案 > 导入模块时如何解决问题?

问题描述

下面是我的文件夹结构。

My_Project
|
+-- Project
     |
     +-- file1.py
     |    
     +-- folder1.py
       |  
       +-- folder2.py
           |
           +--file2.py

谁能帮助我如何将 file2.py 中的 file1.py 作为模块导入?

到目前为止,我已经尝试过使用这样的东西,但它不起作用:

from Project.file1 import some_function which return No module named 'Project'

我也试过:

from ...file1 import some_function

这返回,尝试相对导入,没有父包。

标签: pythondata-science

解决方案


I found this answer by Cameron:

By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

However, you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

Edit: I later found this answer by joey:

Nothing wrong with:

from application.app.folder.file import func_name

Just make sure folder also contains an init.py, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH.


推荐阅读