Python import modules from Zip archives (zipimport)

Use of 'zipimport' module makes it possible to import Python modules and packages from ZIP-format archives. This module also allows an item of sys.path to be a string naming a ZIP file archive. Any files may be present in the ZIP archive, but only files .py and .pyc are available for import. ZIP import of dynamic modules is disallowed.

Functionality of this module is explained by first building a zip archive of files in 'newdir' directory. Following files are assumed to be present in newdir directory

['', '', '', '', '', '', '']

import sys, glob
import zipfile
files = glob.glob("*.py")
print (files)
zf = zipfile.PyZipFile('', mode='w')
for file in files:

We now use '' in rest of the article.

The 'zipimport' module defines zipimporter class in which following methods are defined


This method is the constructor which creates a new zipimporter instance. It requires path to a ZIP filea s argument. ZipImportError is raised if it is not a valid ZIP archive.

>>> import zipimport
>>> importer = zipimport.zipimporter('')


This method earchs for a module specified. It returns the zipimporter instance if the module was found, or None if it wasn’t.

>>> ret=importer.find_module('prime')
>>> ret
<zipimporter object "">
>>> ret=importer.find_module('sample')
>>> ret
>>> print (ret)


This method returns the code object for the specified module, raises ZipImportError if the module couldn’t be found.

>>> prog=importer.get_code('prime')
>>> print (prog)
<code object <module> at 0x022A4650, file "\", line 1>


This method loads the module specified. It returns the imported module, or raises ZipImportError if it wasn’t found.

>>> importer = zipimport.zipimporter('')
>>> mod=importer.load_module('prog')
>>> mod.__name__
>>> mod.__file__
>>> mod.__loader__
<zipimporter object "">


This method returns the source code for the specified module.

>>> prog=importer.get_source('prime')
>>> print (prog)
def isprime(x):
   for i in range(2,x-1):
      if x%i==0:
      return False
return True
f = int(input())
l = int(input())
primelist = list(filter(isprime, range(f,l)))
print ("prime1", "prime2", "composites")
composites=[(primelist[i-1], primelist[i],(primelist[i]-1)-primelist[i-1]) for i in range(1,len(primelist))]
print (composites)