Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 453
george Avatar asked Oct 01 '15 09:10

george


1 Answers

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

like image 89
Nongi Avatar answered Oct 31 '22 14:10

Nongi