How can I avoid: "ZipFile instance has no attribute '__exit__''" when extracting a zip file?

george picture george · Oct 1, 2015 · Viewed 7.8k times · Source

The code is:

import sys
execfile('test.py')

In test.py I have:

import zipfile
with zipfile.ZipFile('test.jar', 'r') as z:
    z.extractall("C:\testfolder")

This code produces:

AttributeError ( ZipFile instance has no attribute '__exit__' ) # edited

The code from "test.py" works when run from python idle. I am running python v2.7.10

Answer

Nongi picture Nongi · Nov 13, 2015

I made my code on python 2.7 but when I put it on my server which use 2.6 I have this error :

AttributeError: ZipFile instance has no attribute '__exit__'

For solve this problems I use Sebastian's answer on this post : Making Python 2.7 code run with Python 2.6

import contextlib

def unzip(source, target):
    with contextlib.closing(zipfile.ZipFile(source , "r")) as z:
        z.extractall(target)
    print "Extracted : " + source +  " to: " + target

Like he said :

contextlib.closing does exactly what the missing exit method on the ZipFile would be supposed to do. Namely, call the close method