I am trying to use the fileinput.input() module to read in the lines from a bunch of files in a directory and occasionally receive an IOerror exception. What is the best way to handle this exception so that if 1 of the items in the list i'm feeding fileinput,input() generates this IOError, i can get fileinput to simply continue onto the next item in the list ?

When you get IOError,pass make it countinue to end.
Other errors than IOError will raise error as normal.

try:
  doSomething()
except IOError:
  pass

That does not work. Here is my code:

try:
        for line in fileinput.input(newlist):
           num_matches = string.count(line, searchterm)
           if num_matches:                     # a nonzero count means there was a match
               print "found '%s' %d times in %s on line %d." % (searchterm, num_matches,
                   fileinput.filename(), fileinput.filelineno())
    except IOError:
        print "There was a problem with at least 1 of the matches"
        pass

It exits as soon as it hits the first IOError

You must put try around the fileinput that is in try to line "5.5" and indent the print line and 7 to same level as try: (current print indention).

I'm sorry i don't follow :(

Actually I did not realize you are using fileinput as iterator already in for line. To get hat to work I think you must wrap it in function passing IOErrors.

string.count is not also good style, you should use the method of string itself: "abcd".count("a")

After looking the documentation it appears that you can give hook function to method, which can ignore the ioerrors.

After looking the documentation it appears that you can give hook function to method, which can ignore the ioerrors.

??

I posted code snippet how to do it.

I posted code snippet how to do it.

Perhaps i'm losing my mind, but where did you post this code snippet? I don't see it :(

Look code snippet part of the forum. It would maybe be usefull to read my post linked from my signature.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.