Home > database >  Importing files from different folder in the same parent directory
Importing files from different folder in the same parent directory

Time:08-17

I've got a folder that looks something like this. I'm trying to import a class from card.py from test_cards.py

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

In test.py I've tried:

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. 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. 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.

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

from poker.card import Card

Thank you

CodePudding user response:

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.

Here's some more information: https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python

  • Related