import other python file

How to Import Other Python File

Often developers import modules and packages in their Python script. But sometimes you may need to import another python file in your python script. This is required if you have written a custom function or library that you want to be reused at multiple places of your application. There are several ways to do this. In this article, we will learn how to import other python file.


How to Import Other Python File

We will have two separate python file for our purpose – one is the python file that needs to be imported and the other is the file that will import the python file. We will look at two use cases – one where both the python files are in same directory and the second where both are in different directories.

1. Both Files in Same Folder

Let us say you have two python file a.py and b.py in same folder /home/ubuntu/data, and you want to import a.py into b.py. You can do this by adding any of the following lines in your b.py file.

import a
or

from a import *

The above line will completely import a.py to b.py. If you want to import only specific function func_a() from a.py then you can modify the above commands as shown.

from a import func_a

2. Both Files in Different Directory

In this case both files are in separate directories. a.py is present in /home/ubuntu/data and b.py is present in /home/ubuntu. If you want to import a.py to b.py then add the following line to b.py file.

import data.a
or

from data.a import *

If you want to import only specific function func_a() from a.py you can modify the above command as shown.

from data.a import func_a

There are many different ways to import python files into other python files. We have looked at a very simple and easy one. Also it does not use any other module for import.

Here are some other ways to do this.

Using os.system

You can use system() function from os module to import the python file.

import os
os.system("python /path/to/yourfile.py")

Using execfile

You can also use execfile (exec() function in Python 3+) to import python file.

execfile("/path/to/yourfile.py")

In this article, we have learnt some simple ways to import python file to another. You can use any of these methods depending on your requirement.

Also read:

How to Remove Punctuation Marks from String in Python
How to Do Case Insensitive Comparison in Python
How to Remove Duplicates From Array of Objects JavaScript
How to Listen to Variable Changes in JavaScript
How to Reset Primary Key Sequence in PostgreSQL

Leave a Reply

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