In this article you will be able to understand about handling Binary File in python in a very simplified language. Remember the important points and also practice the programs mentioned in the following Handout. So lets start
Binary File in Python
What is Binary File ?
Binary Files 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.
Difference between Binary File and Text File
Text File | Binary File |
These files can be read by human directly | These files can not be read by humans directly. |
Each line is terminated by a special character , known as EOL | No delimiter for a line |
Processing of file is slower than binary file | Processing of file is faster than text file |
Why Binary File in Python?
When ever we want to write a sequence like List or Dictionary to a file then we required binary file in python.
Steps to work with Binary File in Python
- import pickle module.
- Open File in required mode (read, write or append).
- Write statements to do operations like reading, writing or appending data.
- Close the binary file
How to write data in Binary File?
Python provides a module named pickle which help us to read and write binary file in python.
Remember : Before writing to binary file the structure (list or dictionary) needs to be converted in binary format. This process of conversion is called Pickling. Reverse process Unpickling happen during reading binary file which converts the binary format back to readable form.
Q1. Write a function bwrite() to write list of five numbers in a binary file?
Line wise explanation of the above code :
- Line one is just to define our function.
- In line 2 we are importing a module pickle which help to read and write data to binary file.
- In line number 3, we are opening a file named “data.dat” in writing mode and ‘f’ is our file object/handle.
- Line number 4, we are declaring a list which needs to be write in a file.
- This line is doing the main role of writing in a file. dump function of pickle module is used to write list in binary file.
- This line is simply closing the file.
- Last line is to calling function bwrite()
Output of above program
NOTE : Above is the binary file “data.dat” which is not in human readable format.
Q 2. Write a function bwrite() to write list of three names in a binary file?
NOTE : It can be done in the same way as above program, just you need to change the data of list.
Solution:
def bwrite():
import pickle
f = open("data.dat", 'wb')
d = ["Amit", "Sumit", "Naina"]
pickle.dump(d,f)
f.close()
bwrite() # calling function
Q3. Write a program to write the following dictionary in a binary file. d = {1 : "Amit", 2 : "Sumit", 3 : "Naina"} Solution: def bwrite(): import pickle f = open("data.dat", 'wb') d = {1 : "Amit", 2 : "Sumit", 3 : "Naina"} pickle.dump(d,f) f.close() bwrite()
In binary format the “data.dat” will look like below and you can see that data is not in much readable format.
How to read data in Binary File?
Python provides a module named pickle which help us to read binary file in python.
Q4. Write a program to read data from file “data.dat” (created above in Q3)
def b_read( ):
f = open("data.dat" , "rb")
import pickle
d = pickle.load(f)
print(d)
b_read( )
Q5. Write a function empadd() which will add a record of employee in a binary file “data.dat” using list. Data to be add include employee name, employee number. Also write a function empread() which will read all the records from the file.
def empadd(): # This function is for adding record to a file f = open("data.dat","wb") import pickle d = [ ] ename=input("Enter employee name") en = int(input("Enter employee number")) temp=[ename, en] d.append(temp) d1 = pickle.dump(d,f) # This line is actually writing content to file f.close() #This line breaks the connection of file handle with file def empread(): #This function is for reading data from file f=open("data.txt","rb") import pickle d = pickle.load(f) for i in d: print(d) f.close() empadd() # This statement is calling a function to add new record empread() # This statement is calling a function to read all the records
Practice Session:
Q1. Differentiate between binary and text file.
Ans. Try Yourself
Q2. Name a function which is used to write data in binary file.
Ans. Try Yourself
Q3. Which module is to be import to read and write data in binary file.
Ans. Try Yourself
Q4. Accept 10 numbers from the user and write in a binary file “data.dat”
Ans. Try Yourself
Q5. Write a function addrecord() to add record of teacher in file “teacher.dat” Each record should contain the following data (using list) :
- Teacher Name
- Teacher designation
- Teacher Salary
SOLUTION
Q6. Write a function displayrec() to read and display the record of a particular teacher according to the name entered by the user from a file “teacher.dat” (created above)
SOLUTION
Q6. Write a function deleterec() to read and display the record of a particular teacher according to the name entered by the user from a file “teacher.dat” (created above)
Conclusion :
Read the above handout carefully and should know to handle the binary file in following ways
- How to store data in binary file?
- How to read data from binary files?
- How to search a particular record in binary file?
- How to delete a particular record from binary file?
- How to update a particular record in binary file?
TOTAL MCQ – 10
TOTAL MARKS – 10
CLICK TO START QUIZ-#1
TOTAL MCQ – 15
TOTAL MARKS – 15
CLICK TO START QUIZ-#2
Disclaimer : I tried to give you the correct content of Binary File in Python but if you feel the content is not correct, feel free to contact me at csiplearninghub@gmail.com
Class 12 Computer Science Sample Paper 2020-2021.
Class 12 Computer Science Sample Paper Marking Scheme
Class 12 Computer Science Test Series
Best notes for class 12
Thank you