Check sibling questions
Computer Science - Class 12
Chapter 2 - File Handling in Python

A file sports.dat contains information in following formal Event Participant. Write a function that would read contents from file sports.dat and creates a file named Athletics. dat copying only those records from sports.dat where the event name is “Athletics”

 

Answer:

def athletic ():

    f1=open( "sports.dat" , 'r' )

    f2=open( "Athletics.dat" , 'w' )

    l=f1.readlines()

    for line in l:

        if line.startswith( "Athletics" ):

            f2.write(line)

            f2.write( "\n" )

    f1.close()

    f2.close()

Question 2-A file sports - Teachoo.JPG

File sports.dat:

image3.png

File Athletics.dat:

image4.png

Introducing your new favourite teacher - Teachoo Black, at only ₹83 per month


Transcript

Question 2 A file sports.dat contains information in following formal Event Participant. Write a function that would read contents from file sports.dat and creates a file named Athletics. dat copying only those records from sports.dat where the event name is “Athletics” Opens file sports.dat in read mode reading all the lines in the text file and assigning it to ‘l’ Checking if a line starts with the word ‘Athletics’ Closes the 2 files Opens file Athletics.dat in write mode Iterating through each line in ‘l’ and assigning it to ‘line’ If a line starts with the word ‘Athletics’ then that line is written to the file Athletics.dat Invokes the function athletic()

CA Maninder Singh's photo - Expert in Practical Accounts, Taxation and Efiling

Made by

CA Maninder Singh

CA Maninder Singh is a Chartered Accountant for the past 12 years. He also provides Accounts Tax GST Training in Delhi, Kerala and online.