0

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 ?

3
Contributors
10
Replies
11
Views
5 Years
Discussion Span
Last Post by pyTony
0

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

try:
  doSomething()
except IOError:
  pass
0

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

Edited by Skrell: n/a

0

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).

0

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")

Edited by pyTony: n/a

0

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

0

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

??

0

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 :(

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.