Keep trying

Yesterday I remembered a problem that I had with the following try/except block.

try:
zfile = zipfile.ZipFile(sfile)
except:
print("Problem with %s" %sfile)
return(None)

With this code the original error messages were supressed and there was no way I could tell what exactly went wrong. If the file is missing or if it is not a valid zip file the error message would be the same.
The problem was that I used the except without specifying the error I am trying to catch.

A somewhat better code would be:

try:
zfile = zipfile.ZipFile(sfile)
except IOError:
print("File %s does not exist" %sfile)
return(None)
except zipfile.BadZipfile:
print("File %s is not a zip file" %sfile)
return(None)

The casing of zipfile.BadZipfile was not obvious and I did struggle with it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s