I have code in one folder, and want to import code in an adjacent folder like this:
I am trying to import a python file in innerLayer2, into a file in innerLayer1 outerLayer: innerLayer1 main.py innerLayer2 functions.py I created the following function to solve my problem, but there must be an easier way? This only works on windows aswell and I need it to work on both linux and windows.
# main.py import sys def goBackToFile(layerBackName, otherFile): for path in sys.path: titles = path.split('\\') for index, name in enumerate(titles): if name == layerBackName: finalPath = '\\'.join(titles[:index+1]) return finalPath + '\\' + otherFile if otherFile != False else finalPath sys.path.append(goBackToFile('outerLayer','innerLayer2')) import functions Is there an easier method which will work on all operating systems?
Edit: I know the easiest method is to put innerLayer2 inside of innerLayer1 but I cannot do that in this scenario. The files have to be adjacent.
Edit: Upon analysing answers this has received I have discovered the easiest method and have posted it as an answer below. Thankyou for your help.