Help to Import file from Parent directory Python


I have a list of directories as such:

--> simple_games

On : "/data_struct/simple_games/" , I am trying to import 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!

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
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!