# 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(textfile, search_str): line_num = 0 total_matches = 0 matched_lines = [] for line in textfile: line_str = line.strip().lower() line_len = len(line_str) line_num += 1 matches = multi_find(line_str, search_str, 0, line_len) if matches: num_matches = matches.count(',') + 1 total_matches += num_matches matched_lines.append([line_num, line_str]) return [total_matches, matched_lines] def print_result(filename, total_matches, matched_lines_list, output_file): print('*** File searched =', filename, file=output_file) print('*** Total matches =', str(total_matches), file=output_file) for line_num, line_str in matched_lines_list: print('{:4d} {}'.format(line_num, line_str), file=output_file) print(file=output_file) # the main program search_str = input('search for: ') search_str = search_str.lower() output_file = open('output.dat', 'w') for filename in get_files(): # search the file input_file = open(filename, 'r') total_matches, matched_lines_list = search(input_file, search_str) input_file.close() # print the results print_result( filename, total_matches, matched_lines_list, output_file ) output_file.close()