Question

Based on the with statement

  • The context manager’s __exit__() is loaded for later use.
  • The context manager’s __enter__() method is invoked.

I have seen one of the with usage with zipfile

Question> I have checked the source code of zipfile located here:

/usr/lib/python2.6/zipfile.py

I don't know where the __enter__ and __exit__ functions are defined?

Thank you

Was it helpful?

Solution

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

Usage:

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

If you type

help(MyZipFile)

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!

OTHER TIPS

zipfile.ZipFile is not a context manager in 2.6, this has been added in 2.7.

Example of creating a class using object class:

class ZipExtractor(object): # Create class that can only extract zip files
  def __init__(self, path): # Initial part
    import zipfile # Import old zipfile
    self.Path = path # To make path available to all class
    try: open(self.Path, 'rb') # To check whether file exists
    except IOError: print('File doesn\'t exist') # Catch error and print it
    else: # If file can be opened
      with open(self.Path, 'rb') as temp:
        self.Header = temp.read(4) # Read first 4 bytes
        if self.Header != '\x50\x4B\x03\x04':
          print('Your file is not a zip archive!')
        else: self.ZipObject = zipfile.ZipFile(self.Path, 'r')

  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 our class

  def SuperExtract(member=None, path=None):
    '''Used to extract files from zip archive. If arg 'member'
    was not set, extract all files. If path was set, extract file(s)
    to selected folder.'''
    print('Extracting ZIP archive %s' % self.Path) # Print path of zip
    print('Archive has header %s' % self.Header) # Print header of zip
    if filename=None:
      self.ZipObject.extractall(path) # Extract all if member was not set
    else:
      self.ZipObject.extract(mamber, path) # Else extract selected file

  def close(self): # To close our file
    self.ZipObject.close()

Usage:

with ZipExtractor('/path/to/zip') as zfile:
  zfile.SuperExtract('file') # Extract file to current dir
  zfile.SuperExtract(None, path='/your/folder') # Extract all to selected dir

# another way
zfile = ZipExtractor('/path/to/zip')
zfile.SuperExtract('file')
zfile.close() # Don't forget that line to clear memory

If you run 'help(ZipExtractor)', you will see five methods:

__init__, __enter__, __exit__, close, SuperExtract

I hope I've helped you. I didn't test it, so you might have to improve it.

cat-plus-plus is right. But if you want, you can write your own class to add "missed" features. All you need to do is to add two functions in your class (which is based on zipfile):

def __enter__(self):
  return(self)
def __exit__(self, exc_type, exc_val, exc_tb):
  self.close()

That should be enough, AFAIR.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top