farmdev

fileinput : nice module for file processing

Of late I've been writing scripts that scrape logs to fix data. groan. Well, at least this was a nice discovery: the fileinput module in stdlib (since 2.3? not sure). Some code ...

import fileinput

outf = None
def add_woot(line):
    global outf
    if outf is None:
        outf = open("woots.txt",'w')
    outf.write(line)
    
def main():
    for line in fileinput.input():
        if line.startswith('woot:'):
            add_woot(line)
    if outf:
        print "wrote %s !" % outf.name
        outf.close()
    else:
        print "no woots"
        
if __name__ == '__main__':
    main()

Add optparse in and you just whipped up a nice little script.