[英]Unable to import Python file from another folder
我有一個看起來像這樣的回購
dev ---> common ---> utils.py
---> scripts --> upload_to_blob.py
當我嘗試從 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'
我在 Anaconda 中使用 Python 3.6 env 與基礎 Python 2.7
默認情況下,您不能。 導入文件時,Python 僅搜索當前目錄、入口點腳本運行的目錄和 sys.path,其中包括 package 安裝目錄等位置(實際上比這要復雜一點,但涵蓋了大多數情況)。
但是,您可以在運行時添加到 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
在您的目錄中有__init__.py
文件,您可以訪問其他文件。
dev -
|- common
| |- utils.py
| |- __init__.py
|- scripts
| |- upload_to_blob.py
| |- __init__.py
|- __init__.py
如果要從文件中包含,可以使用如下
from common.utils import *
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.