2

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 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for the resources and explanation, but given that this is pretty clearly all one package it might be more elegant to make GAME a package. Not that that is mutually exclusive with making Player a package.
GAME is also package but good if we make init.py in all sub directories, If you use any modern editor like pycharm than if you create any code directory than it'll automatically make init file so it'll be usefull for importing any module from any directory.
Im confused, how do I then import GAME.Player.player?
It's clear in answer you can use from Player import player after creation of blank init file and than you can use it just like player.METHOD or player.VARIABLE
0

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.

8 Comments

GAME doesn't have a init.py file, should I just make one?
Yes. You don't have to put anything in it if you don't want to. A blank file will work.
Okay but how doe I do the GAME.Story.introduction because the name of the folder is called Blind Universe should I turn it into a string?
It doesnt work. I change the Parent Folder name to BlindUniverse and from BlindUniverse.Player.player import Player doesnt work.
how does it fail? Is it ModuleNotFoundError?
|