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

Remove Ads
Teachoo · Class 12 Explore Class 12

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()

Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.