Computer Science - Class 12
Chapter 2 - File Handling in Python

Write a function to write numbers into a binary  file and read the same.

 

Answer:

def binary_file ():

    import pickle

    f=open( 'data.dat' , 'wb' )

    while True :

        x=int(input( "Enter a number: " ))

        pickle.dump(x,f)

        more=input( 'Want to enter more numbers? Enter Y is yes: ' )

        if more.upper() != 'Y' :

            break

    f.close()

print( "Reading from the binary file" )

f=open( 'data.dat' , 'rb' )

try :

        while True :

            output=pickle.load(f)

            print(output)

    except EOFError:

        pass

    f.close()

Question 1-Write a function - Teachoo.JPG

Go Ad-free

Transcript

Question 1 Write a function to write numbers into a binary file and read the same. Declaring function binary_file() Opens the binary file in write mode & assigns it to file_object ‘f’ Writes to the binary file Closes the binary file Reads data from the binary file and assigns it to ‘output’ Closes the binary file Output Importing the pickle module to access binary files Accepts a user input and assigns it to ‘x’ Opens the binary file in read mode and assigns it to file_object ‘f’ Invokes the function binary_file()

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