Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipfile module error: File is not a zip file

Tags:

python

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

Anybody know why this error is occurring?

like image 851
P'sao Avatar asked Dec 27 '22 20:12

P'sao


2 Answers

You are missing a

file.close()

after the first for loop.

like image 148
bbtrb Avatar answered Jan 13 '23 12:01

bbtrb


Better style than explicit file.close() is to use with-style context handler (supported by zipfile since v2.7), making for much more elegant idiom, where you can't ever forget the implicit close()

By the way, don't ever name a local variable something like file which is likely to shadow globals and give very weird 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
like image 35
smci Avatar answered Jan 13 '23 11:01

smci