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?
- Text Files
- Binary Files
- CSV Files
- 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