How to import files from different folder python

If there are many folders in your project. It would difficult to import from this file to other file. At this article, I will give you 2 ways to do this

How Python search module path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

Importing files from different folder by using module

You should append the folder path and do import normally.

[sourcecode language=”python” wraplines=”false” collapse=”false”] import sys
sys.path.append(‘/ufs/guido/lib/python’)
import abc # abc inside python folder
[/sourcecode]

 

Importing files from different folder by using package

For example, our project directory

Project Structure
Project Structure

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Users of the package can import individual modules from the package, for example:

This loads the submodule sound.effects.echo. It must be referenced with its full name.

An alternative way of importing the submodule is:

This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:

Yet another variation is to import the desired function or variable directly:

Again, this loads the submodule echo, but this makes its function echofilter() directly available:

Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportErrorexception is raised.

Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

2 Replies to “How to import files from different folder python”

Leave a Reply

Your email address will not be published. Required fields are marked *