Help to Import file from Parent directory Python

Hi!

I have a list of directories as such:

data_struct
--> stack.py
--> node.py
--> simple_games
      --> my_game.py

On : "/data_struct/simple_games/my_game.py" , I am trying to import stack.py as such:
<< from ..stack import Stack >>, but I get this error:

ImportError: attempted relative import with no known parent package

Can someone please explain to me how to import from a file from a parent directory in python?

Thanks for your time!
@neuralx

In general, it’s better to structure your directories so that you don’t have to do this. You can usually just do this by rearranging your files or you can have a main script that runs from the root directory and imports what you need from the child directories.

If for some reason you really can’t restructure your directories, you can modify sys.path using something like this:

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from stack import Stack

For more information on this, check out this excellent blog post on the topic. Your problem is discussed in the section called “Case 4: Importing from Parent Directory”, but I’d recommend reading through the whole post as it covers most of the scenarios you’re likely to encounter.

Happy coding!

1 Like

Thank you @el_cocodrilo!