Search code examples
pythonimportpygamepython-importpython-3.7

How I can Import from a other relative folder wihout the knowledge of the path?


I am working on a little video game in Pygame. I want it to be very clear in the folder hierarchy, so, I've already prepare it in this way :

Python 
   Project 
      bin
        init.py
        Project.vbs
      lib
        constants.py
        definitions.py
      sprites ( useless for topic )
      Project.exe

The Project.exe is a ink file, a fake executable. In fact, it's a shortcut to the Project.vbs with open the init.py (It's just for have the clearest folder managment).

What is my problem? I want to import the difinitions.py and the constants.py from the init.py which is in 'bin' folder, it's just absolutely critical for the game. By The way, the files are saved on my USB key but the path of this one always change:

On my own computer, it's C:/user/Save19/Python/...

On my high school computers, it's P:/documents/Python ( internship )

On my phone it's /storage/0/Python/...

And anytime I made a copy, the path change...

So I've read a lot of topics for try to fix that but anytime it's not working :/

I've try it by using :

Import constants from lib import constants from lib.definitions import * I've try ths with the os and the path

import sys sys.path.insert(0, 'Project/lib') import constants

import sys sys.path.append('Project/lib') import constants

But it not working anyway... Can somebody give me a solution and explain me it?


Solution

  • It really depends from where you're starting the Python process. Whatever path you're adding should be relative to that location. So you say it's started from within bin and so you can add

    import os
    import sys
    
    sys.path.append(os.path.abspath('../lib'))
    import constants
    

    You can also add __init__.py to lib and then add ".." to path and do import lib.constants as constants.

    Or you can setup and install the whole thing as a Python package and then use absolute imports such as import mygame.lib.constants as constants.