How to import from a folder in a parent directory?

Viewed 61

I want to import something from a file which is in a folder which is in the Parent Directory.

This is what the directory structure looks like.

GAME
|--Player
|    `player.py  [FILE THAT NEEDS TO BE IMPORTED]
|--Story
|    `introduction.py [FILE NEEDS AN IMPORT STATEMENT]
|--mainGame.py

I know that to import player.py from the Player folder. I need to do import Player.player, but I don't know how to navigate to a different folder in the parent directory.

Please help.

2 Answers

Just need init.py file (blank file also work, no need to enter any code in this) in directory whose file you want to import.

so your directory structure will be like

GAME/
├── mainGame.py
├── Player
│   ├── __init__.py
│   └── player.py
└── Story
    └── introduction.py

and you can import by from Player import player or import Player.player.

It's good to have all directory in package have init file so you can use it anywhere in project/package.

for more information of python package, PYTHONPATH visit here, this(for basic of python packages) it's good blog to understand python project structure.

If GAME is a package (meaning it has an __init__.py file) then you can do import GAME.Story.introduction or import GAME.Player.player.

You can just add the __init__.py file to make it a package if it doesn't already have one. It doesn't have to contain anything, it can just be a blank file.

Running packages can be a bit odd. Running them from inside them doesn't work. To run it navigate to the directory above GAME and run the file you want to with python -m GAME.Story.introduction. Otherwise I expect you will get a ModuleNotFoundError.

Related