简体   繁体   中英

How to tell if python's ZipFile.writestr() failed because file is full?

Without using zip64 extensions, a Zip file cannot be more than 2GB in size, so trying to write to a file that would put it over that limit won't work. I expected that when such a writing was attempted, it would raise an exception, but I've not been able to cause one to be raised. (The documentation is silent on the matter.) If an exception doesn't get raised in such a circumstance, how would I (efficiently) go about determining if the write succeeded or not?

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!"

This isn't ideal, of course, but it might serve as a temporary solution until a better one has been found. Again, I don't think this is a very good way of using zip. But if there is no appropriate exception (which there should), it might serve as a temporary solution.

I've got an exception trying to write big strings to a zip archive:

$ 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

Using the script:

#!/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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM