q0987 q0987 - 1 year ago 70
Python Question

where is the __enter__ and __exit__ defined for zipfile?

Based on the with statement

  • The context manager’s
    is loaded for later use.

  • The context manager’s
    method is invoked.

I have seen one of the with usage with zipfile

I have checked the source code of zipfile located here:


I don't know where the
functions are defined?

Thank you

Answer Source

I've added this as another answer because it is generally not an answer to initial question. However, it can help to fix your problem.

class MyZipFile(zipfile.ZipFile): # Create class based on zipfile.ZipFile
  def __init__(file, mode='r'): # Initial part of our module
    zipfile.ZipFile.__init__(file, mode) # Create ZipFile object

  def __enter__(self): # On entering...
    return(self) # Return object created in __init__ part
  def __exit__(self, exc_type, exc_val, exc_tb): # On exiting...
    self.close() # Use close method of zipfile.ZipFile


with MyZipFile('new.zip', 'w') as tempzip: # Use content manager of MyZipFile
  tempzip.write('sbdtools.py') # Write file to our archive

If you type


you can see all methods of original zipfile.ZipFile and your own methods: init, enter and exit. You can add another own functions if you want. Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download