CBSE Class 12 Computer Science Question 76 of 136

Data File Handling — Question 15

Back to all questions
15
Question

Question 15

A file 'sports.dat' contains information in the following format: EventName, Participant

Write a function that would read contents from file 'sports.dat' and create a file named 'Athletic.dat' copying only those records from 'sports.dat' where the event name is "Athletics".

Answer

Let the file "sports.dat" include the following sample records:

Athletics - Rahul
Swimming - Tanvi
Athletics - Akash
Cycling - Kabir
Athletics - Riya
def filter_records(input_file, output_file):
    with open(input_file, 'r') as f_in:
        with open(output_file, 'w') as f_out:
            for line in f_in:
                event, participant = line.strip().split(' - ')
                if event == 'Athletics':
                    f_out.write(line)

filter_records('sports.dat', 'Athletic.dat')

The file "Atheletic.dat" includes following records:

Athletics - Rahul
Athletics - Akash
Athletics - Riya