Search code examples
pythonpython-3.xvariablespython-import

Import script from another folder without knowing the precise path


I have two files F1.py and F2.py with the following structure:

                      |-----F2.py
                      |
             |-----Folder2
             |
[...]-----Folder1
             |
             |-----F1.py

F1.py simply executes F2.py as if an app, but F2.py need variable from F1.py to run, so how am i supposed to do it ?

F2 is it's own separate app, for exemple a timer, while F1 is a launcher. F1 automatically checks for all .py files in Folder2 and creates button for each of them so you can run them.

I've tried doing from Folder1.F1 import var1, var2 but it just runs F1. Also, since the data I need is created during the run of the app and dependant on user input, I need to get the data while F1.py runs.

Also, I don't know what comes before Folder1 so there's that.


Solution

  • I recreated your folder structure like this:

    folder1/
    |-- py1.py
    |-- folder2/
    |   |-- py2.py
    

    In py1.py I have the following code:

    text = 'Hello World!'
    

    In py2.py I have this code:

    import sys
    import os
    
    # Get the path of the parent directory (project_folder)
    parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    sys.path.append(parent_dir)
    
    from py1 import text
    
    print(text)
    

    This is the output when I execute py2.py:

    Hello World!
    

    I hope this works for you!