Using relative imports in python with mutliple parent and children folders
Question: I had a small problem with importing a script that was in a parent folder, but
I managed to resolve it using:

    
    
    import sys
    sys.path.append("../")
    

My directory is like this:

    
    
    Data
    |->->code
         |->->script1.py
         |->->->->subfolder
                  |->->->script2.py
    

When I run script2 (which imports script1) from the subfolder directory, the
script runs without problems. But if I try to run script2 from the code
directory using:

    
    
    :~ ./subfolder/script2.py
    

I get an error :

    
    
    ImportError: No module named script1
    

I tried using relative imports but because my code is not structured in
packages it doesn't work. Is there a way I can run script2 from both
directories (the parent and the child) and still be able to import script1
everytime?

Thank you in advance, Georgi Nikolov

**EDIT** : Ok, after I read through all the suggestions, I did a "simple" hack
which is quite ugly in my opinion but works quite well:

    
    
    import sys
    parent_folder = sys.path[0].split("/subfolder")[0]
    sys.path.append(parent_folder)
    import script1
    

Now I can even call script2 from the root and it will manage to import script1


Answer: To import a module that is up a level, you can use this.

    
    
    import os, sys
    sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
    

**An Explanation**

    
    
    __file__            # The full path to your running file.
    os.path.dirname     # See below. (1)
    os.path.join        # See below. (2)
    sys.path.append     # See below. (3)
    ".."                # Universal for "up a level".
    

  1. `os.path.dirname(path)` -

> [Return the directory name of pathname
> path.](https://docs.python.org/2/library/os.path.html#os.path.dirname)

  2. `os.path.join(path, *paths)` -

> [Join one or more path components
> intelligently.](https://docs.python.org/2/library/os.path.html#os.path.join)

  3. `sys.path` -

> [A list of strings that specifies the search path for
> modules.](https://docs.python.org/2/library/sys.html#sys.path)

You can add a string with the `append` method.

