[英]Unable to import Python file from another folder
I have a repo that looks like this我有一个看起来像这样的回购
dev ---> common ---> utils.py
---> scripts --> upload_to_blob.py
It gives following error when I try to import utils from common当我尝试从 common 导入 utils 时出现以下错误
Traceback (most recent call last):
File "scheduled_scripts/upload_to_blob.py", line 6, in <module>
from common import utils
ModuleNotFoundError: No module named 'common'
I am using Python 3.6 env in Anaconda with base Python 2.7我在 Anaconda 中使用 Python 3.6 env 与基础 Python 2.7
By default, you cannot.默认情况下,您不能。 When importing a file, Python only searches the current directory, the directory the entry point script runs from, and sys.path which includes locations like the package installation directory (it's actually a little more complicated than that, but that covers most cases).
导入文件时,Python 仅搜索当前目录、入口点脚本运行的目录和 sys.path,其中包括 package 安装目录等位置(实际上比这要复杂一点,但涵盖了大多数情况)。
However, you can add to the Python path at runtime:但是,您可以在运行时添加到 Python 路径:
# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, 'scheduled_scripts/upload_to_blob.py')
import file
Have __init__.py
files in your directories and you can access the other files.在您的目录中有
__init__.py
文件,您可以访问其他文件。
dev -
|- common
| |- utils.py
| |- __init__.py
|- scripts
| |- upload_to_blob.py
| |- __init__.py
|- __init__.py
if you want to include from the file, you can use like below如果要从文件中包含,可以使用如下
from common.utils import *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.