Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing modules from a neighbouring folder in Python

I have put the question in the figure below:

enter image description here

EDIT The question put next to the figure is:

How do I make script_A1 import a function from script_B2?

Similar questions have been asked before. But most answers suggest to add the module/script/package(whatever) to the PATH variable. For example:

sys.path.append('...')

But adding the module to the PATH variable just feels so wrong. I do not want to alter my system in any way. When my application closes, I want my Python environment to be clean and 'untouched'. I'm afraid that adding uncontrolled modules to the PATH variables on my system will cause headaches later on.

Thank you for helping me out :-)

like image 240
K.Mulier Avatar asked Apr 18 '16 18:04

K.Mulier


People also ask

How does Python import modules from some other directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

How do I import one module to another in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

How do I import a module from one package to another?

To import a module from another path, you first need to import the sys module as well as any other Python modules that you would like to use in your program. The sys module is provided by the Python Standard Library and it provides functions and parameters that are system-specific. The path.

What are the three ways to import modules in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.


1 Answers

You can use a trick of adding the top folder to path:

import sys
sys.path.append('..')
import folderB.something

You can also use imp.load_source if you prefer.

like image 56
Ronen Ness Avatar answered Oct 12 '22 14:10

Ronen Ness