import fileinput

#prepare empty file to open in case of IOerror
open('dummy', 'w').close()

def hook_skip_IOerror(filename, mode):
        try:
            return open(filename, mode)
        except IOError:
            print("There was a problem with opening %s" % filename)
            return open('dummy', mode)          

def process(searchterm):
    for line in fileinput.input(openhook=hook_skip_IOerror):
        if line is not None:
           num_matches = line.count(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())

process('=')

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

Actually the line 15, while does not disturb, does nothing, as it is from before I realized I must always return file object. So it should be removed and rest of the function unindented for clean code.

Ok now that i've found your code, as I am a newb, would you mind explaining the openhook concept a bit as i don't full grasp it?

What does process('=') do ? And what does opening a 'dummy' file accomplish? Does it allow the function to continue by replacing the unreadable file with a dummy one that IS readable ?

Edited 5 Years Ago by Skrell: n/a

The action in function is based in your own code only made it run as you gave no definition off searchterm. So of course it tells accurances of = in line making it easy to test the script with bunch of Python files as arguments.

You did read fileinput documentation? I use the mention that empty files are opened and closed immediately, to pass the bad file with warning message from program

Edited 5 Years Ago by pyTony: n/a

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.