How to log error to file, and not fail on exception

Viewed 114266

I am downloading a file from the net, and it fails even though I am doing:

for p in query:

try:

except IOError as e:
   print e;

If there is an error, I want to log it, and then continue on with the next file.

In this loop, I am trying to download an image, if for some reason the filename was bad, or the website was down, etc., I want to continue with the next item in the for loop.

Is there a more generic error that won't fail and continue processing?

Also, how can I log errors to a file?

4 Answers

This will write your error to a log file and continue to run the code.

import traceback

#This line opens a log file
with open("log.txt", "w") as log:

    try:
        # some code
        # Below line will print any print to log file as well.
        print("Creating DB Connection", file = log)
    except Exception:
        traceback.print_exc(file=log)
        continue
Related