How do I check if a zip file is corrupt or not? I have a zip file with 10 jpg images. I am able to extract say 8 of the images. Two of the images in the zip are corrupt and I am not able to extract those. Is there a way to check for this in a Python script?
Advertisement
Answer
This code will either throw an exception (if the zip file is really bad or if it’s not a zip file), or show the first bad file in the zip file.
JavaScript
x
20
20
1
import sys
2
import zipfile
3
4
if __name__ == "__main__":
5
args = sys.argv[1:]
6
7
print("Testing zip file: %s" % args[0])
8
9
try:
10
the_zip_file = zipfile.ZipFile(args[0])
11
ret = the_zip_file.testzip()
12
if ret is not None:
13
print("First bad file in zip: %s" % ret)
14
sys.exit(1)
15
except Exception as ex:
16
print("Exception:", ex)
17
sys.exit(1)
18
19
print("Zip file is good.")
20