Home > database >  Converting text value to module type in Python
Converting text value to module type in Python

Time:01-02

I am trying to see if the libraries has been installed in the python environment with the below code.

import os
libraries=['pandas','paramico','fnmatch'] #list of libraries to be installed 
for i in libraries:
    print("Checking the library", i ," installation")
    try:
       import i
       print("module ", i ," is installed")
    except ModuleNotFoundError:
       print("module ", i, " is not installed")

The array values are not being converted to module type and everything is showing not installed, so how to convert the text values from the array to module type.

In the above example pandas and paramico are not installed but fnmatch is installed.

CodePudding user response:

Use importlib.import_module:

import os
import importlib

libraries=['pandas','paramico','fnmatch'] #list of libraries to be installed 
for i in libraries:
    print("Checking the library", i ," installation")
    try:
       importlib.import_module(i)
       print("module ", i ," is installed")
    except ModuleNotFoundError:
       print("module ", i, " is not installed")

Output example:

Checking the library pandas  installation
module  pandas  is installed
Checking the library paramico  installation
module  paramico  is not installed
Checking the library fnmatch  installation
module  fnmatch  is installed
  • Related