python - Importing files from different folder

ID : 452

viewed : 249

Tags : pythonimporterrorpython-importpython

Top 5 Answer for python - Importing files from different folder

vote vote


Note: This answer was intended for a very specific question. For most programmers coming here from a search engine, this is not the answer you are looking for. Typically you would structure your files into packages (see other answers) instead of modifying the search path.

By default, you can't. When importing a file, Python only searches the directory that the entry-point script is running from and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

However, you can add to the Python path at runtime:

# import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '/path/to/application/app/folder')  import file 
vote vote


Nothing wrong with:

from import func_name 

Just make sure folder also contains an, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH.

vote vote


When modules are in parallel locations, as in the question:

application/app2/some_folder/ application/app2/another_folder/ 

This shorthand makes one module visible to the other:

import sys sys.path.append('../') 
vote vote


First import sys in

 import sys 

Second append the folder path in

sys.path.insert(0, '/the/folder/path/name-package/') 

Third Make a blank file called __ init in your subdirectory (this tells Python it is a package)

  • name-package
    • __ init

Fourth import the module inside the folder in

from name-package import name-module 
vote vote


I think an ad-hoc way would be to use the environment variable PYTHONPATH as described in the documentation: Python2, Python3

# Linux & OSX export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH  # Windows set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH% 

Top 3 video Explaining python - Importing files from different folder