Check sibling questions
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

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


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

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.