Search code examples
pythonvisual-studio-codepathsys

Python: Adding Directory One Level Up to System Path


I already have a solution to this problem, but just want to make sure it's the optimal one and doing what I think it's doing. I have a folder structure like this:

Main
+ data
++ __init__.py
++ get_data.py
+ work
++ stuff.py

get_data.py has a class named GetData that I need to import. I'm in stuff.py. When I use:

from data.get_data import GetData

It does not work. So I did this:

sys.path.append(".")

If I do that, my code works. However, it looks a bit odd when I look at the paths via:

print(sys.path)

I get this:

['C:\\Main\\Notebooks', '.']

I think what I'm doing is taking the current working directory and appending that path one level higher. And this works. Is this correct? Is there a more optimal solution?


Solution

  • You could try to add the following statement at the beginning of the file:

     import os,sys 
     sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    

    It adds the path of the module that needs to be imported to the system path.

    enter image description here