开发者

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 _Rea开发者_如何学JAVAlGetContents
    raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file

Anybody know why this error is occurring?


You are missing a

file.close()

after the first for loop.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜