简体   繁体   English

从同一父目录中的不同文件夹导入文件

[英]Importing files from different folder in the same parent directory

I've got a folder that looks something like this.我有一个看起来像这样的文件夹。 I'm trying to import a class from card.py from test_cards.py我正在尝试从 test_cards.py 的 card.py 导入 class

└── 32-PROJECT-Texas-Hold-Em-Poker/
├── poker/
│   ├── card.py
│   └── __init__.py
└── tests/
    └── test_cards.py
    └── __init__.py

In test.py I've tried:在 test.py 我试过:

from poker import card

from .poker import card

from ..poker import card
from 32-PROJECT-Texas-Hold-Em-Poker.poker import card


import sys
sys.path.insert(1, '/path/to/Test_folder_1/Test_folder_2')
from Test_folder_2 import add_numbers

but it keeps coming up with either No module named poker or ImportError: attempted relative import with no known parent package .但它不断出现No module named pokerImportError: mapped relative import with no known parent package I've tried different variations along with varying where the init .py file is, and honestly I've tried a lot more than what I posted above.我尝试了不同的变体以及改变init .py 文件的位置,老实说,我尝试的比我上面发布的要多得多。 I've read up on relative and absolute imports.我已经阅读了相对和绝对进口。 Short of adding this directory right into my path, I'm completely lost at what seems to be a simple task.没有将此目录添加到我的路径中,我完全迷失在看似简单的任务中。 I've spend a couple of days on this now and I just can't seem to get it to work.我现在已经花了几天时间,但我似乎无法让它发挥作用。 Also, what should I be studying to understand this stuff better rather than finding stuff online?另外,我应该学习什么来更好地理解这些东西,而不是在网上找东西? I've just recently learnt about system paths and venvs.我最近刚刚了解了系统路径和 venvs。

I'm actually following along with The complete Python bootcamp for 2022 on Udemy from test_cards.py, he is able to get a Card class from card.py just from typing实际上,我正在关注来自 test_cards.py 的 Udemy 上 2022 年完整的 Python 训练营,他只需键入即可从 card.py 获得卡片 class

from poker.card import Card

Thank you谢谢

There are a few ways to do this.有几种方法可以做到这一点。 Here's one that's quite simple, suitable for test code but not recommended in a production app:这是一个非常简单,适合测试代码但不推荐在生产应用程序中使用的代码:

import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'poker'))
import card
sys.path = sys.path[:-1]

That should work no matter where you run your Python script from.无论您从哪里运行 Python 脚本,这都应该有效。

Here's some more information: https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python这里有更多信息: https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM