• Home
  • Courses
  • School
  • Programs
  • Problems
  • Contact Us
  • My account
  • Register

Have any question?

(+91) 98222 16647
info@simplycoding.in
RegisterLogin
Simply Coding
  • Home
  • Courses
  • School
  • Programs
  • Problems
  • Contact Us
  • My account
  • Register

Python File Handling

Questions on Binary File Handling in Python

  • Categories Python File Handling, Python

In this post we will cover Binary File Handling in Python. You can watch our video on Binary File Handling in Python – Click Here.

Q.1 What is Binary File?
Ans. Binary Files contain raw data so are not in human readable format. It can be read by using some special tool or program. Binary files may be any of the image format like jpeg or gif, or word, excel, ppt files etc. 

Q.2 What mode you need to use to open Binary file? Also give the Syntax for same.
Ans. While opening any binary file we have to specify ‘b’ in file opening mode.
           Syntax:
                               f1=open(“one.bin”,”wb”)- to open the file in write mode
                               f1=open(“two.bin”,”rb”)- to open the file in read mode

Q.3 What is pickle module?
Ans. Pickle module provides us with the ability to serialize and deserialize objects, i.e., to convert objects into bitstreams which can be stored into files and later be used to reconstruct the original objects.

  • Pickle library is developed using the C programming language like the python interpreter is.
  • It can save complex Python data structures.

Q.4 Why we use pickle module?
Ans.

  • It is very difficult for us to write several types of objects into the binary file.
  • This is very difficult task, particularly if some of the objects can have variable lengths
  • We cannot read the contents of the file later.
  • To overcome this problem we use pickle module.
  • It can store lists, Tuples, dictionaries, sets, classes etc.

Q. 5 What is Pickling or Serialization?
Ans. Serialization is the process of transforming data or an object in memory (RAM) to a stream of bytes called byte streams. These byte streams in a binary file can then be stored in a disk or in a database or sent through a network. Serialization process is also called pickling.

Q.6 What is De-serialization or unpickling?
Ans. De-serialization or unpickling is the inverse of pickling process where a byte stream is converted back to Python object.

Q.7 What is pickle.dump()?
Ans.

  • dump() function is used to store the object data to the file.
  • dump( object, filehandle )
  • It takes 3 arguments.
    • First argument is the object that we want to store.
    • The second argument is the file object we get by opening the desired file in write-binary (wb) mode.
    • the third defines the protocol.

Q.8 What is pickle.load()?
Ans.

  • load() function is used to retrieve pickled data.
  • mylist = pickle.load(filehandle)
  • Arguments
  • The primary argument is the filehandle that you get by opening the file in read-binary (rb) mode.

Q.9 Which of the following file types allows us to store large data files in the computer memory?

  1. Text Files
  2. Binary Files
  3. CSV Files
  4. None of these

Ans. b

Q. 10 Write a program to write Name and Roll Nos into a binary file
Ans.

import pickle
with open ("file.dat", "wb") as F1:
    while True:
        op = int (input ("Enter 1 to add data, 0 to quit"))
        if (op == 1):
            name = input ("Enter name : ")
            rollno = int (input ("Roll no : "))
            pickle.dump([name,rollno],F1)
        elif op == 0:
            break

Q. 11 Write a program to read name and roll no from a binary file. The file has data as list [name,rollno]
Ans.

import pickle
F1 =  open ("file.dat", "rb")
while True:
    try:
        l = pickle.load(F1)
        print (l)
    except EOFError:
        break
F1.close()

Q. 12 Write a code to show how a dictionary is stored as binary file.
Ans.

import pickle
F1 = open ("file.dat", "wb")
Icode = input ("Enter code : ")
quantity = int (input ("Quantity : "))
d = {Icode:quantity},
pickle.dump(d, F1)      
F1.close()

Q. 13 Write a code that reads from a file “sales.dat” which has following information [itemcode, amount] Read from the file and find the sum of the amount.
Ans.

import pickle
F1 =  open ("sales.dat", "rb")
sum = 0
while True:
    try:
        l = pickle.load(F1)
        sum = sum + l[1]
    except EOFError:
        break
print (sum)
F1.close()

Q. 14 A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a function countrec() in Python that would read contents of the file “salary.DAT” and display the details of those employee whose salary is above 20000.
Ans.

def countrec():
    num=0
    fobj=open("data.dat","rb")
    try:
        print("Emp id\tEmp Name\tEmp Sal")
        while True:
            rec=pickle.load(fobj)
            if rec[2]>20000:
                print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
    except:
        fobj.close()
countrec()

Q.15 A file sports.dat contains information in following format [event, participant].
Write a program that would read the contents from file and copy only those records from sports.dat where the event name is “Athletics” in new file named Athletics.dat                         

Ans.

import pickle
F1 =  open ("sports.dat", "rb")
F2 =  open ("athletics.dat", "wb")
sum = 0
while True:
    try:
        l = pickle.load(F1)
        if (l[0].lower() == "athletics"):
            print (l)
            pickle.dump(l,F2)
    except EOFError:
        break
F1.close()
F2.close()

Q. 16 A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage]. Write a function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose percentage is above 75. Also display number of students scoring above 75%.
Ans.

import pickle
def countrec():
   fobj=open("student.dat","rb")
   num = 0
   try:
      while True:
         rec=pickle.load(fobj)
         if rec[2]>75:
         num = num + 1
         print(rec[0],rec[1],rec[2])
   except:
      fobj.close()
   return num
  • Share:
author avatar
Simply Coding

Previous post

Questions on Text File Handling in Python
June 13, 2021

Next post

HTML Audio and Video tags
June 14, 2021

You may also like

Python function
Python function
3 July, 2021
for & while
Learn Python for & while
19 June, 2021
Queue
Python Queue
17 June, 2021

Leave A Reply Cancel reply

You must be logged in to post a comment.

Categories

  • Uncategorized
  • Programs
    • Python
    • Java
  • Problems
    • Python
    • Java
    • Web Development
      • Internet
    • Emerging Technologies
  • Notes
    • General
    • QBasic
    • MS Access
    • Web Development
      • XML
      • HTML
      • JavaScript
      • Internet
    • Database
    • Logo Programming
    • Scratch
    • Emerging Trends
      • Artificial Intelligence
      • Internet of Things
      • Cloud Computing
      • Machine Learning
    • Computer Fundamentals
      • Computer Networks
      • E-Services
      • Computer Hardware
    • Python
    • Java
  • School
    • ICSE
      • Computers Class 9
        • Java Introduction
        • Tokens & Data Types
        • Java Operators
        • Math Library
        • if & switch
        • For & While
        • Nested loops
      • Computer Class 10
        • Sample Papers
        • OOPS concepts
        • Functions in Java
        • Constructors
        • Arrays in Java
        • Strings in Java
    • SSC
      • IT Class 11
        • IT Basics
        • DBMS
        • Web Designing
        • Cyber Laws
      • IT Class 12
        • Web Designing
        • SEO
        • Advanced JavaScript
        • Emerging Tech
        • Server Side Scripting
        • E-Com & E-Gov
      • Computer Science 11
      • Computer Science 12
    • CBSE
      • Computer 9
        • Basics of IT
        • Cyber Safety
        • Scratch
        • Python
      • Computer 10
        • Sample Papers
        • Networking
        • HTML
        • Cyber Ethics
        • Scratch
        • Python
      • Computer Science 11
        • Computer Systems
        • Python 11
          • Python Basics
          • Python Tokens
          • Python Operators
          • Python if-else
          • Python loops
          • Python Strings
          • Python List
          • Python Tuple
          • Python Dictionary
          • Python Modules
        • Data Management
      • Computer Science 12
        • Sample Papers
        • Python 12
          • Python Functions
          • Python File Handling
          • Python Libraries
          • Python Recursion
          • Data Structures
        • Computer Networks
        • Data Management
    • ISC
      • Computer Science 11
        • Introduction to Java
        • Values & Data Types
        • Operators
        • if & switch
        • Iterative Statements
        • Functions
        • Arrays
        • String
        • Data Structures
        • Cyber Ethics
      • Computer Science 12
        • Sample Papers
        • Boolean Algebra
        • OOPS
        • Wrapper Classes
        • Functions
        • Arrays
        • String
Simply Coding Computer Courses for School                Privacy Policy     Terms of Use     Contact Us

© 2021 Simply Coding

Login with your site account

Lost your password?

Not a member yet? Register now

Register a new account

Are you a member? Login now