Zipfile module error: file is not a zip file

I have this code:

# File: zipfile-example-1.py

import zipfile,os,glob

file = zipfile.ZipFile("Apap.zip", "w")

# list filenames
for name in glob.glob("C:\Users/*"):
    print name
    file.write(name,os.path.basename(name),zipfile.ZIP_DEFLATED)
file = zipfile.ZipFile("Apap.zip", "r")
for info in file.infolist():
    print info.filename, info.date_time, info.file_size, info.compress_size

which produces this error:

raceback (most recent call last):
  File "C:/Users/Desktop/zip.py", line 11, in <module>
    file = zipfile.ZipFile("Apap.zip", "r")
  File "C:\Python27\lib\zipfile.py", line 712, in __init__
    self._GetContents()
  File "C:\Python27\lib\zipfile.py", line 746, in _GetContents
    self._RealGetContents()
  File "C:\Python27\lib\zipfile.py", line 761, in _RealGetContents
    raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file

Does anyone know why this error occurs?

+3
source share
2 answers

You are lacking

file.close()

after the first cycle for.

+6
source

An improved style than explicit file.close()is to use the with-style context handler (supported by zipfile from v2.7), making a more elegant idiom where you can never forget the implicitclose()

By the way, never call a local variable something like file, which is likely to be a shadow global and give very strange debugging behavior.

So something like:

import zipfile,os,glob

with zipfile.ZipFile("Apap.zip", "w") as f:    
    for name in glob.glob("C:\Users/*"):
        print name
        f.write(name,os.path.basename(name),zipfile.ZIP_DEFLATED)
# `with` causes an implicit f.close() here due to its `exit()` clause

with zipfile.ZipFile("Apap.zip", "r") as f:
    for info in f.infolist():
        print info.filename, info.date_time, info.file_size, info.compress_size
+3
source

All Articles