我有这段代码:
# 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
产生此错误:
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
有人知道为什么会出现这个错误吗?
答案 0 :(得分:7)
你错过了
file.close()
在第一个for
循环之后。
答案 1 :(得分:3)
比显式file.close()
更好的风格是使用with
- 样式上下文处理程序(自v2.7以来受zipfile支持),使得更加优雅的成语,你永远不会忘记隐含close()
顺便说一句,不要将file
之类的局部变量命名为可能影响全局变量并给出非常奇怪的调试行为。
所以,比如:
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