Write a function that would read contents from file sports.dat and creates a file named Atheletic.dat copying only those records from sports.dat where the event name is “Athletics”.
Here’s a function that reads the contents from the file “sports.dat” and creates a file named “Athletic.dat” by copying only those records where the event name is “Athletics”:
def copy_athletics_records(input_file, output_file): with open(input_file, 'r') as file_in: with open(output_file, 'w') as file_out: for line in file_in: event, participant = line.strip().split('-') if event.strip() == 'Athletics': file_out.write(line) input_file = 'sports.dat' output_file = 'Athletic.dat' copy_athletics_records(input_file, output_file)
In this program, the
copy_athletics_records function takes two parameters:
input_file (the name of the input file, i.e., “sports.dat”) and
output_file (the name of the output file, i.e., “Athletic.dat”). It reads the input file line by line, strips any leading or trailing whitespace using
.strip(), and splits each line into two parts using the
- delimiter. The event name and participant are extracted from each line. If the event name is “Athletics” (after stripping any whitespace), the line is written to the output file. Only records with the event name “Athletics” are copied to the output file.