0
votes

I wanted to get the comment data of Zip files from an entire folder, but when ever it encounters any other file besides a Zip file it gives me an error:

Traceback (most recent call last): File "C:\Users\user\Desktop\New folder\ec5.py", line 11, in with ZipFile(zfile, 'r') as testzip: File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\zipfile.py", line 1200, in init self._RealGetContents() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\zipfile.py", line 1267, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file

Is it possible to fix it useing anything along the lines of:

try:

exception

This is the code:

import os

import unicodedata

from zipfile import ZipFile
rootFolder = u"C:/Users/user/Desktop/archives/"

zipfiles = [os.path.join(rootFolder, f) for f in os.listdir(rootFolder)]
for zfile in zipfiles:
    print("Opening: {}".format(zfile))
    with ZipFile(zfile, 'r') as testzip:
        print(testzip.comment) # comment for entire zip
        l = testzip.infolist() #list all files in archive
        for finfo in l:
            # per file/directory comments
            print("{}:{}".format(finfo.filename, finfo.comment))
1

1 Answers

2
votes

Try this

for zfile in zipfiles:
    print("Opening: {}".format(zfile))
    try:
        with ZipFile(zfile, 'r') as testzip:
            print(testzip.comment) # comment for entire zip
            l = testzip.infolist() #list all files in archive
            for finfo in l:
                # per file/directory comments
                print("{}:{}".format(finfo.filename, finfo.comment))
    except BadZipFile:
        print("Bad file:", zfile)

you may need to import BadZipFile exception from zipfile

You can also use catch-all exception but I would discourage it as it may hide other errors there:

except Exception as e:
    print(e)