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

Go Ad-free

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 has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo