Fileinput from files ignoring incorrect ones.

TrustyTony 0 Tallied Votes 948 Views Share

Learned about hook functions for a thread having problem with bad user input from the documentation. This is result which skips bad inputs.

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('=')
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

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.

Skrell 0 Light Poster

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?

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

What you catched from fileinput documentation?

Skrell 0 Light Poster

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 ?

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

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

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.