Make python code continue after exception

I am trying to read all files from a folder that meets certain criteria. My program crashes after I have an exception. I try to continue, even if there is an exception, but it still stops executing.

This is what I get in a couple of seconds.

error <type 'exceptions.IOError'> 

Here is 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 
+8
python
source share
3 answers

Put your try/except structure in other blocks. Otherwise, when you receive an error message, it will break all cycles.

Perhaps after the first for loop add try/except . Then, if an error occurs, it will continue with the subsequent 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 great example of why you should use the with statement here to open files. When you open a file with open() , but an error is thrown, the file remains open forever. Now 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 the error is caught, the file will be closed, as the with statement does.

+26
source share

Move try / except inside the for loop. How in:

  import os path = 'C:\\' listing = os.listdir(path) 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: print "error "+str(IOError) 
+3
source share

You are a code that does exactly what you say to it. When you get an exception, it goes into this section:

 except: print "error "+str(IOError) pass 

Since nothing happens after this, the program ends.

Also, pass is redundant.

+2
source share

All Articles