Importing files

Started by allisonsinger, September 10, 2025, 05:49:52 AM

Previous topic - Next topic

allisonsinger

*
Newbie
Posts: 1
Logged
Hello,
I've been working on developing a game for about a week, but I'm encountering some problems with importing separate files. I would greatly appreciate any help!
Directory Structure:
/
    Games
        BattleGame
            BattleGame.py
            characters.py
            moves.py
Should I keep everything in a single file? I've noticed that most other games are structured this way. I'd prefer to separate data from the game logic, but I don't want to compromise on resources. How can I import a file from the same game directory? I keep encountering a "module not found" error no matter what I try.
I've tried the following:
from moves import moves
from Games.BattleGame.moves import moves

AyreGuitar

*
Newbie
Posts: 2
Logged
Try doing this to set the current directory to your game folder before importing your modules:
from os import chdir
chdir("/Games/BattleGame/")
Then you should be able to import normally, eg:
from moves import moves

muchpile6768s

*
Newbie
Posts: 1
Logged
Quote from: allisonsinger on September 10, 2025, 05:49:52 AMHello,
I've been working on developing a game for about a week, but I'm encountering some problems with importing separate files. I would greatly appreciate any help!
Directory Structure:
Code Select Expand
/
    Games
        BattleGame
            BattleGame.py
            characters.py
            moves.py
Should I keep everything in a single file? I've noticed that most other games are structured this way. I'd prefer to separate data from the game logic, but I don't want to compromise on resources. How can I import a file from the same game directory? I keep encountering a "module not found" error no matter what I try.
I've tried the following:
Code Select Expand top games
from moves import moves
from Games.BattleGame.moves import moves
It looks like your structure should work, but the issue is probably related to how you're running the script. If you run **BattleGame.py** directly, Python may not treat the parent folders as packages. One common fix is to add an empty `__init__.py` file inside the **Games** and **BattleGame** folders so Python recognizes them as modules. Then you can usually import with something like `from moves import moves` if the files are in the same directory. Another option is running the script from the project root and using `from Games.BattleGame.moves import moves`. In general, keeping files separated like you're doing is actually good practice, especially as the project grows, so I wouldn't recommend putting everything into one file.

SMF spam blocked by CleanTalk