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 and in same folder /home/ubuntu/data, and you want to import into You can do this by adding any of the following lines in your file.

import a

from a import *

The above line will completely import to If you want to import only specific function func_a() from 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. is present in /home/ubuntu/data and is present in /home/ubuntu. If you want to import to then add the following line to file.

import data.a

from data.a import *

If you want to import only specific function func_a() from 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/")

Using execfile

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


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 *