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

Learn in your speed, with individual attention - Teachoo Maths 1-on-1 Class


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

Ask a doubt
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 13 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.