×

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 Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

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.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.