[Python] Importing python files from other directories?

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a resource mining game at the moment, and I want players to be able to easily add "expansions" to the game which add on more resources or mechanics. I have a structure that looks like this:

    Saltminer/
    gameData/
    main.py
    mods/
    saltResource/
    saltData.py
    saltConfig.py
    stoneResource/
    stoneData.py
    stoneConfig.py
    icon.ico


    I need a way for the main.py file to access the variables contained within all of the "<resource>Config.py" files and all of the "<resource>Data.py" files.

    To try this, I tried using the import function, having set a variable in saltData called testVariable...

    from mods import *
    print(saltData.testVariable)


    And I got an error saying that saltData is not defined.

    I also tried:

    from mods import *
    print(saltResource.saltData.testVariable)


    And got the following error:

    Traceback (most recent call last): File "C:\gameData\main.py", line 2, in <module> print(saltResource.saltData.testVariable) ^^^^^^^^^^^^ NameError: name 'saltResource' is not defined

    Continue reading...

Compartilhe esta Página