Search code examples
pythonimportsubdirectory

Import file python from multiple subfolders


How can I import the file file2.py from the file file1.py? Is there a standard method without necessarily using libraries such as sys?

project\
  folder1\
    folder2\
      file1.py
  folder3\
    folder4\
      file2.py

Solution

  • you are best going to use an absolute import so you make sure that your project is inside your sys.path and then you can just import project.folder1.folder2.file1 without having to do it relative to file2,

    if you are working on a package that is not in your python path then I suggest that you make a virtual environment and a setup.py file (look up setuptools for more info) and if you have activated your virtual environment and then run python setup.py install (or python setup.py develop to use it from the source directory if you are still working on it) then it will be in your sys.path, - note there are equivalent commands with pip install . if you prefer

    otherwise if you don't want to do it the "proper" way, you will just have to fiddle with sys.path by hand, and yes you will have to import sys before you can do that or set PYTHONPATH environment variable before you start python (colon separated list of directories and you will want to include the parent directory of project)