Question:
Write a python program to print only those lines in a list of files that has a particular word
Here, I am looking for a word ‘print’ in a list of python files.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def readfiles(filenames): for f in filenames: for line in open(f): yield line def grep(pattern, lines): return (line for line in lines if pattern in line) def printlines(lines): for line in lines: print line, def main(pattern, filenames): lines = readfiles(filenames) lines = grep(pattern, lines) printlines(lines) main('print',['factorial.py','GCD.py','LCM.py','password.py','rect.py']) |
Explanation:
Generator Expressions are generator version of list comprehensions. They look like list comprehensions, but returns a generator back instead of a list.
Output:
1 2 3 4 5 6 7 |
print "Sorry, factorial does not exist for negative numbers" print "The factorial of 0 is 1" print "The factorial of",num,"is",factorial(num) print "The H.C.F. of", n1,"and", n2,"is",HCF(n1, n2) print "The L.C.M. of", nos1,"and", nos2,"is", lcm(nos1, nos2) print "Valid passwords",value print "Area of rectangle:",obj.area() |
Leave a Reply