# FILE: search_files.py # AUTHOR: Eugene Wallingford # DATE: 2014/11/01 # COMMENT: Search for occurrences of a string in all files in # a directory. Report total number of matches and # all lines that match. Match strings regardless of # upper- or lowercase. from str_utils import multi_find from homework09 import get_files # possible extension: return the total number of matches in the file # and use to sort the files in a Python list before displaying the # program's output def search(filename, search_str): textfile = open(filename, 'r') search_str = search_str.lower() line_num = 0 total_matches = 0 matched_lines = '' for line in textfile: line_str = line.strip() line_len = len(line_str) line_num += 1 matches = multi_find(line_str.lower(), search_str, 0, line_len) if matches: num_matches = matches.count(',') + 1 total_matches += num_matches matched_lines += '{:4d} {}\n'.format(line_num, line_str) textfile.close() return '*** File searched = ' + filename + '\n' \ + '*** Total matches = ' + str(total_matches) + '\n' \ + matched_lines # the main program search_str = input('search for: ') output = open('output.dat', 'w') for filename in get_files(): print( search(filename, search_str), file=output ) output.close()