我无法从其他文件夹导入模块
I can't import modules from other folders
我对 Python 世界有点陌生。我正在使用 Python3 并且在导入方面遇到困难。
我在 Windows 上使用 PyCharm 编写应用程序。在我切换到 Linux 和 VS Code 之前,一切都在项目中进行。
现在我不能使用绝对导入从同一项目中的其他包导入模块。
例如,我想从模块卡导入所有可用的卡类型。
我测试了类,一切正常。我只遇到导入问题。
The project structure:
/
|-cards
|-__init__.py
|-card.py
|-monster_card.py
|-spell_card.py
|-trap_card.py
|-ritual_card.py
|-deck
|-__init__py
|-deck.py
|-system
# This is the code in __init__.py in cads package
from . trap_card import TrapCard
from . spell_card import SpellCard
from . ritual_card import RitualCard
from . monster_card import MonsterCard
__all__ = [TrapCard, SpellCard, RitualCard, MonsterCard]
# The following line, for example, does not work from inside another package
# I'm trying to import the modules in cards from deck
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
当我尝试从另一个文件夹导入包时,我收到此错误消息:
回溯(最近调用最后):
File "/root/git-repos/Yu-Gi-Oh/decks/deck.py", line 3, in
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
ModuleNotFoundError: No module named 'cards'
当您调用 import *
时,python 从 sys.path
搜索模块。在调用 import stmt.
之前,您需要将根目录添加到 sys.path
对于你的情况,你的根目录是 /
。
喜欢:
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from cards import *
其他方式
将文件 __init__.py
添加到您的根目录中,使其成为一个模块。然后将 from cards import *
更改为 from .cards import *
.
我对 Python 世界有点陌生。我正在使用 Python3 并且在导入方面遇到困难。
我在 Windows 上使用 PyCharm 编写应用程序。在我切换到 Linux 和 VS Code 之前,一切都在项目中进行。
现在我不能使用绝对导入从同一项目中的其他包导入模块。
例如,我想从模块卡导入所有可用的卡类型。
我测试了类,一切正常。我只遇到导入问题。
The project structure:
/
|-cards
|-__init__.py
|-card.py
|-monster_card.py
|-spell_card.py
|-trap_card.py
|-ritual_card.py
|-deck
|-__init__py
|-deck.py
|-system
# This is the code in __init__.py in cads package
from . trap_card import TrapCard
from . spell_card import SpellCard
from . ritual_card import RitualCard
from . monster_card import MonsterCard
__all__ = [TrapCard, SpellCard, RitualCard, MonsterCard]
# The following line, for example, does not work from inside another package
# I'm trying to import the modules in cards from deck
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
当我尝试从另一个文件夹导入包时,我收到此错误消息:
回溯(最近调用最后):
File "/root/git-repos/Yu-Gi-Oh/decks/deck.py", line 3, in from cards import TrapCard, MonsterCard, SpellCard, RitualCard ModuleNotFoundError: No module named 'cards'
当您调用 import *
时,python 从 sys.path
搜索模块。在调用 import stmt.
sys.path
对于你的情况,你的根目录是 /
。
喜欢:
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from cards import *
其他方式
将文件 __init__.py
添加到您的根目录中,使其成为一个模块。然后将 from cards import *
更改为 from .cards import *
.