close

How to import another python script (.py) into main python file

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to import another python script (.py) into main python file in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to import another python script (.py) into main python file?

  1. How to import another python script (.py) into main python file?

    To include the dictionary, you could do this if your file location is in different directory (with caution of path.append

  2. import another python script (.py) into main python file

    To include the dictionary, you could do this if your file location is in different directory (with caution of path.append

Method 1

To include the dictionary, you could do this if your file location is in different directory (with caution of path.append

import sys
sys.path.append("path/foo/bar/")
from light import *

If it is in same directory as current directory, you could just do:

from light import *

Method 2

The syntax for importing your_filename.py, assuming it is in the same directory, is

import your_filename

In your case, it would be

import light

Note the absence of .py.

If your file is in a different directory, you’ll need to do:

import sys
sys.path.append('path/to/dir/containing/your_filename.py')
import your_filename

Note that appending to sys.path is dangerous, and should not be done unless you know what you’re doing.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read