# year/month/day,visitors,prospects event_file = open('attendance.txt','r') reportfile = open('report_by_year.txt','w') # for the year-wise report visitors = 0 prospects = 0 num_lines = 0 year_str = '' # for processing the year visitors_for_year = 0 # for processing the year for event_str in event_file: num_lines += 1 event_str = event_str.strip() date,visitors_str,prospects_str = event_str.split(',') visitors += int(visitors_str) prospects += int(prospects_str) # process the year if year_str == '': year_str = date[0:4] visitors_for_year = 0 elif year_str != date[0:4]: print('{} total visitors {:3d}'.format(year_str,visitors_for_year), \ file=reportfile) year_str = date[0:4] visitors_for_year = 0 visitors_for_year += int(visitors_str) # print the final year print('{} total visitors {:3d}'.format(year_str,visitors_for_year), \ file=reportfile) print() print('Visitors {:3d} average {:2.2f}'.format(visitors, visitors/num_lines)) print('Prospects {:3d} average {:2.2f}'.format(prospects, prospects/num_lines)) event_file.close() reportfile.close() # for the year-wise report