I'm trying to read all files from a folder that matches a certain criteria. My program crashes once I have an exception raised. I am trying to continue even if there's an exception but it still stops executing.
This is what I get after a couple of seconds.
error <type 'exceptions.IOError'>
Here's my code
import os path = 'Y:\\Files\\' listing = os.listdir(path) try: for infile in listing: if infile.startswith("ABC"): fo = open(infile,"r") for line in fo: if line.startswith("REVIEW"): print infile fo.close() except: print "error "+str(IOError) pass
Perhaps after the first for-loop, add the try/except . Then if an error is raised, it will continue with the next file. This is a perfect example of why you should use a with statement here to open files. When you open the file using open() , but an error is catched, the file will remain open forever.
Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.
Put your try/except
structure more in-wards. Otherwise when you get an error, it will break all the loops.
Perhaps after the first for-loop, add the try/except
. Then if an error is raised, it will continue with the next file.
for infile in listing: try: if infile.startswith("ABC"): fo = open(infile,"r") for line in fo: if line.startswith("REVIEW"): print infile fo.close() except: pass
This is a perfect example of why you should use a with
statement here to open files. When you open the file using open()
, but an error is catched, the file will remain open forever. Now is better than never.
for infile in listing: try: if infile.startswith("ABC"): with open(infile,"r") as fo for line in fo: if line.startswith("REVIEW"): print infile except: pass
Now if an error is caught, the file will be closed, as that is what the with
statement does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With