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

94

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:

# some_file.py 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

90

Nothing wrong with:

from application.app.folder.file import func_name 

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

vote vote

76

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

application/app2/some_folder/some_file.py application/app2/another_folder/another_file.py 

This shorthand makes one module visible to the other:

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

62

First import sys in name-file.py

 import sys 

Second append the folder path in name-file.py

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

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

  • name-file.py
  • name-package
    • __ init __.py
    • name-module.py

Fourth import the module inside the folder in name-file.py

from name-package import name-module 
vote vote

50

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







Related QUESTION?