Make python code continue after exception

后端 未结 3 1386
情深已故
情深已故 2021-02-01 02:53

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 exc

相关标签:
3条回答
  • 2021-02-01 03:00

    You're code is doing exactly what you're telling it to do. When you get an exception, it jumps down to this section:

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

    Since there's nothing after that, the program ends.

    Also, that pass is superfluous.

    0 讨论(0)
  • 2021-02-01 03:09

    Move the try/except inside the for loop. Like 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)
    
    0 讨论(0)
  • 2021-02-01 03:27

    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.

    0 讨论(0)
提交回复
热议问题