import os
targtxt = input('Now you under directory \'test\',Type the word you wanna search...\n')
resul = []
def checkfile(targtxt, txtfile):
"""
targtxt is a string including the word/phrase from the user, to be searched with in this program.
txtfile is a textIOWrapper.
return a turple:
1st element :True if this txtfile includes targtxt, False on the contrary.
2nd element :In which line the word is found, return -1 if not found.
"""
line = 0
for l in txtfile.readlines():
if targtxt in l:
return (True,line)
else:
line += 1
else:
return (False, -1)
for sec in os.walk('./test/'):
if sec[2] == []:
continue
else:
for filename in sec[2]:
with open( os.path.join(sec[0],filename), 'r' ) as txtfile:
ans = checkfile(targtxt, txtfile)
if ans[0]:
resul.append("Line %d in file %s under %s" % (ans[1], filename, sec[0] ) )
for ans in resul:
print(ans)
杨钰博