Python import python file into another python file














































Python import python file into another python file



Python Import python file into another python file


Importing python file into another python file can be done in many ways.

IMPORTING FILE IN A SAME LOCATION:


METHOD 1:

import functionality:


Step 1:

Example:

def merge():
k = {"a" : 1, "b" : 2}
d = {"d" : 3, "e" : 4}
e={**k,**d}
return e
print(merge())
Let's save it in C:/Users/Raji/Documents/Python Scripts/f ile1.py

Step 2:

from file1 import merge
merge()
Save it in C:/Users/Raji/Documents/Python Scripts/f ile2.py

Step 3:

Run file2.py




METHOD 2:

Import module using python interpreter:


Step 1:

def wish():
print('hello')
Let's save it in C:/Users/Raji/Documents/Python Scripts/f ile1.py

Step 2:

Run file1.py in python interpreter




METHOD 3:

Using 'exec':


Step 1:

def wish():
print('hello')
Let's save it in C:/Users/Raji/Documents/Python Scripts/f ile1.py

Step 2:

exec('C:UsersRajiDocumentsPython Scriptsile1.py')
wish()
Save it in C:/Users/Raji/Documents/Python Scripts/f ile2.py

Step 3:

Run file2.py 

>>>import file2.py
hello


IMPORTING FILE IN A DIFFERENT LOCATION:


Step 1:

Example:

def merge():
k = {"a" : 1, "b" : 2}
d = {"d" : 3, "e" : 4}
e={**k,**d}
return e
print(merge())
Let's save it in C:/Users/Raji/Documents/Python Scripts/Python /file1.py

Step 2:

from file1 import merge
merge()
Save it in C:/Users/Raji/Documents/Python Scripts/f ile2.py

Step 3:

Run file2.py




Comments