ValueError: Attempt to use ZIP archive that was already closed

By Jennifer, 7 months ago
  • Bookmark
0

Extracting zip using python module ZipFile get following error. how to solve this error?


>>> from zipfile import ZipFile
>>> import os
>>> os.chdir("path")  # path of file
>>> file="Demo.zip"   # file name
>>> with ZipFile(file,'r') as zip:     #ZipFile constructor; READ mode; ZipFile object named as zip
    zip.printdir()                     #To print contents of the archive
print("Extracting files")
    zip.extractall()                   #Extract contents of the ZIP to the current working directory
print("Finished extracting")

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-4a82e06694a5> in <module>
      6         zip.printdir()                      #To print contents of the archive
      7 print("Extracting files")
----> 8 zip.extractall()                    #Extract contents of the ZIP to the current working directory
      9 print("Finished extracting")

~\Anaconda3\lib\zipfile.py in extractall(self, path, members, pwd)
   1614 
   1615         for zipinfo in members:
-> 1616             self._extract_member(zipinfo, path, pwd)
   1617 
   1618     @classmethod

~\Anaconda3\lib\zipfile.py in _extract_member(self, member, targetpath, pwd)
   1667             return targetpath
   1668 
-> 1669         with self.open(member, pwd=pwd) as source, \
   1670              open(targetpath, "wb") as target:
   1671             shutil.copyfileobj(source, target)

~\Anaconda3\lib\zipfile.py in open(self, name, mode, pwd, force_zip64)
   1453         if not self.fp:
   1454             raise ValueError(
-> 1455                 "Attempt to use ZIP archive that was already closed")
   1456 
   1457         # Make sure we have an info object

ValueError: Attempt to use ZIP archive that was already closed

ValueError
Zip
Python
1 Answer
0

You need to indent your code so that all accesses to  statement are within the with statement.

as follows:

from zipfile import ZipFile
import os
os.chdir("path")
file="demo.zip"
with ZipFile(file,'r') as zip:     #ZipFile constructor; READ mode; ZipFile object named as zip
    zip.printdir()                 #To print contents of the archive
    print("Extracting files")
    zip.extractall()               #Extract contents of the ZIP to the current working directory
    print("Finished extracting")

Your Answer

Webinars

Live Masterclass on "Python for Artificial Intelligence"

Dec 4th (7:00 PM) 213 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More