如何判断python的ZipFile.writestr()是否因文件满而失败?
在不使用zip64扩展的情况下,一个Zip文件的大小不能超过2GB,所以如果你试图写入一个会让它超过这个限制的文件,就会失败。我原以为在尝试这样写入的时候,会出现一个错误提示,但我一直没能遇到这样的情况。(相关文档对此没有说明。)如果在这种情况下没有错误提示,我该如何有效地判断写入是否成功呢?
2 个回答
0
import os
size = os.path.getsize("file") #Get the size of the file.
size = size/1073741824 #Converting bytes to GB.
if size < 2: # < is probably safer than <=
#do the zipping
else:
print "The file is too large!"
这当然不是最好的办法,但在找到更好的解决方案之前,这可能算是一个临时的解决办法。再说一次,我觉得这样使用zip并不是很理想。不过,如果没有合适的例外处理(其实应该有的),那这个方法可能就只能当作一个临时的解决方案了。
0
我在尝试将大字符串写入一个压缩文件时遇到了一个异常:
$ python write-big-zip.py
Traceback (most recent call last):
File "write-big-zip.py", line 7, in <module>
myzip.writestr('arcname%d'% i, b'a'*2**30)
File "/usr/lib/python2.7/zipfile.py", line 1125, in writestr
self._writecheck(zinfo)
File "/usr/lib/python2.7/zipfile.py", line 1020, in _writecheck
raise LargeZipFile("Zipfile size would require ZIP64 extensions")
zipfile.LargeZipFile: Zipfile size would require ZIP64 extensions
使用的脚本:
#!/usr/bin/env python
"""Write big strings to zip file until error."""
from zipfile import ZipFile
with ZipFile('big.zip', 'w') as myzip:
for i in range(4):
myzip.writestr('arcname%d'% i, b'a'*2**30)