在导入语句中使用文件路径 python
Using file paths in import statements python
我的文件结构为:
mainprogram.py
/Scripts
Data.py
文件 Data.py
在文件夹 Scripts
中,其中包含一组函数,mainprogram.py
正在尝试导入这些函数。
如果 Data.py
与文件 mainprogram.py
位于同一文件夹中,那么我可以简单地编写 from Data import *
并且我将从文件中获得所有已定义的函数。
但是,我总是收到错误消息:ModuleNotFoundError: No module named '__main__.Scripts'; '__main__' is not a package
如果我尝试从脚本文件夹导入它。
我尝试了多种方法,包括:from .Scripts.Data import *
和 from \Scripts\Data import *
我是不是遗漏了什么,或者是否有更好的方法从子文件夹中导入 Data.py
?
看看https://docs.python.org/2/tutorial/modules.html:
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.
您的 Scripts
文件夹中需要一个 __init__.py
文件(空)。然后,你应该可以 import Scripts.Data
.
我的文件结构为:
mainprogram.py
/Scripts
Data.py
文件 Data.py
在文件夹 Scripts
中,其中包含一组函数,mainprogram.py
正在尝试导入这些函数。
如果 Data.py
与文件 mainprogram.py
位于同一文件夹中,那么我可以简单地编写 from Data import *
并且我将从文件中获得所有已定义的函数。
但是,我总是收到错误消息:ModuleNotFoundError: No module named '__main__.Scripts'; '__main__' is not a package
如果我尝试从脚本文件夹导入它。
我尝试了多种方法,包括:from .Scripts.Data import *
和 from \Scripts\Data import *
我是不是遗漏了什么,或者是否有更好的方法从子文件夹中导入 Data.py
?
看看https://docs.python.org/2/tutorial/modules.html:
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.
您的 Scripts
文件夹中需要一个 __init__.py
文件(空)。然后,你应该可以 import Scripts.Data
.