×

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module in python is a combination of definitions which include functions and constants and statements that refer to those definitions. When the module code is written, and it is written in such a way that it can reused in any type of other module by importing it.

The simplest way to create a python module is by creating a file with a filename which is having the .py extension. The import statements wont work if the given extension is not followed and rather than we need to import another library from python i.e., importlib and writing the code in it.

To understand the standard usage of import, let's create a file with the following extension .py with the name hello.py and deploy the code as follow.

Code:

def hello_world()
print( ‘python hello’ )

Now, there is no need of writing always the given code for the desired required output because if we need it, we can just simply import the given module rather than writing the whole code again. The main feature of this is we can change a single line of code inside the module rather than changing and displaying this message in the hello.py module.

Importing File in the same Directory:

We have two python files in the same directories namely following as:

Folder name: tutorilandexample

Python files:

  • hello.py
  • Python2.py

The following files contain the code as the hello.py contains the above code and to recall the hello_world function from python2.py, we can deploy the new code in python2.py.

Code:

import hello
hello.hello_world()

here, in the import statements we used a name, and it is simply the modules filename without .py extension to it.

Import a File in a Subdirectory:

Importing a module in sub directories is possible only in the python versions python 3.3 and above versions. If the version is older than 3.3, we need to follow some steps by creating another sub directory and importing the file in different directory.

Python version 3.3 above, we don’t need to create another sub-dir.

We can directly import it into python2.py. let’s create a sub directory as subdir.

Code:

import subdir.hello
subdir.hello.say_hello ()

NOTE:

While declaring the system path, we separate the system components using / (or) \ but in python import we separate components using a dot symbol (.)

We can also import module as declaring as any variable by using import as.

Code:

import subdir.hello as m
m.say_hello ()

here, m is chosen as importing subdir module.

Importing a file from multi-level sub directories is also possible not only from single level.
Example:

Now, we create two level of directories namely as pythonA & pythonB and let’s assume we have the following level as.

Code:

  tutorialandexample/
       pythonA/
          pythonB/
                   hello.py
                       python2.py

and for this to access the .py files we can deploy code as:

Code:

import pythonA.pythonB.hello as hello
hello.say_hello ()

Import a File in a Different Directory:

Now let’s try with a other case by moving the module to another directory that is not in the path tree. But python itself by default looks and searches the files in all the directories and all the standard locations defined in system path.

We need use append function to write in our old module.

Code:

import sys
sys.path. append (‘/pythonA/pythonB’ )
import hello
hello.say_hello ()

To append we need to use absolute path because the file is present in different directory so we need to define the path from the root of the file system rather than using the relative path. We can also use __file__ to get the full file.

Code:

import os
import sys


python2_dir = os. path.dirname(__file__ )
hello_dir = os. path.join( python2_dir, '..', 'pythonA', 'pythonB' )
sys. path. append(hello_dir)
import hello


hello.say_hello ()

Importing a file with no .py extension:

To utilize this function body, we need have the python version 3.4 and above because this version provides a built-in library known as importlib. This allows us to open and load any file even if it is a python module with no .py extension

Now, we remove extensions from the python files and proceed with the importlib library.

import importlib.machinery
import importlib.util


loader = importlib. machinery.SourceFileLoader( 'hello', '/pythonA/pythonB/hello' )


spec = importlib.util.spec_from_loader( 'hello', loader )
hello = importlib.util.module_from_spec( spec )
loader.exec_module( hello )


# Use hello
hello.say_hello()

Related Topics

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Python String count() method

Python String count() method The string.count() method returns the number of times a specified value appears in the string. Syntax string.count(sub[, start[, end]]) Parameter sub: This parameter represents a substring to be searched. start: This parameter...

1 minute read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.