Python Import Modules with Example

Python import modules can also use functions, classes, and variables defined in other files. An import statement is used for a per-define function, so the user also defines the function. I will have some examples of import module concepts deep into that.

employee_name = "Mario"
age = "55"
salary= 100000

def details():
    print("Employee name is:  ", employee_name)
    print("Employee age is: ", age)
    print("Employee title is:  ", salary)

 Import entire module and import class and function syntax is below.

## import entrie json modules 

import json

## import class param 
from employee import details, employee_name, age, salary

 importing alias name and all modules, classes and functions

#importing alias name

import module_name as alias_name
alias_name.function_name()

#import all modules classes and functions
from module_name import *

We will have employee class data in an employee.py file. Going to the read employee class and write in another file. The Example is below.

import json
from employee import details, employee_name, age, salary

def create_dict(name, age, salary):
   
    ### WRITE SOLUTION HERE
    employee_dict = {}
    employee_dict['first_name'] = str(name)
    employee_dict['age'] = int(age)
    employee_dict['salary'] = str(salary)
    
    return employee_dict
     

def write_json_to_file(json_obj, output_file):
     
    ### WRITE SOLUTION HERE
    with open(output_file, mode='w') as file:
        newfile = file.write(json_obj)
    
    return newfile
   

def main():
     
    employee_dict = create_dict(employee_name, age, salary)
    print("employee_dict: " + str(employee_dict)) 
     
    json_object = json.dumps(employee_dict)
    print("json_object: " + str(json_object))

    # Write out the json object to file
    write_json_to_file(json_object, "employee.json")

if __name__ == "__main__":
    main()

Output


employee_dict: {'first_name': 'sss', 'age': 12, 'salary': '123455'}
json_object: {"first_name": "sss", "age": 12, "salary": "123455"}


Similar Articles