0

Text file data : sponsors.txt file that has stored data with their names and donations

John Smith,230.5
Sally Jones,380
Mary Smith,104.55
David McDougal,165.7
Sally Matthews,184.5
Peter Evans,300.25

Expected Output :

Please enter a search string: Smith
Search returned 2 results:
John Smith,230.5
Mary Smith,104.55

MyCode:

def read_sponsor_data(file_path, word):
    with open(file_path, 'r') as file:
        content = file.read()
        name_count = content.count(list_sponsor)
        if word in content:
            print('Search returned', name_count, 'results:')
        else:
            print('Search returned no results.')
        for i in range(0, name_count):
            print(content)
    file.close()


if search_sponsor == 1:
    list_sponsor = input("Please enter a search string: ")
    read_sponsor_data("sponsors.txt", list_sponsor)
else:
    print("Invalid Input")

My Output :

Please enter a search string: Smith
Search returned 2 results:
John Smith,230.5
Sally Jones,380
Mary Smith,104.55
David McDougal,165.7
Sally Matthews,184.5
Peter Evans,300.25
John Smith,230.5
Sally Jones,380
Mary Smith,104.55
David McDougal,165.7
Sally Matthews,184.5
Peter Evans,300.25

1 Answers1

1

file.read() reads the whole file as a string. This string has the inputed name 2 times. Then you print this whole string 2 times. You probably need file.readlines() or iterate over file (i.e. over lines):

def read_sponsor_data(file_path, word):
    with open(file_path, 'r') as file:
        matched_lines = [l for l in file if word in l]

    if matched_lines:
        print('Search returned', len(matched_lines), 'results:')
        for l in matched_lines:
            print(l)
    else:
        print('Search returned no results.')
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48