BINARY FILE HANDLING
BINARY FILE HANDLING
dump() method is used to write the object in binary file and load() method is used to read the object form file
both methods are available in pickle module
Pickling: pickling is a process where a python object is converted into a byte stream.
Unpickling: unpickling is the inverse of Pickling process where a byte stream is converted into a python object.
Pickling and unpickling is alternatively known as serialization, marshalling, or flattening.
Reading and Writing binary files
1.Write dictionary into a binary file
import pickle
d={'python':90,'java':80,'C++':85}
f=open('abc.dat','wb') # open binary file in write mode
pickle.dump(d,f) # dump d into f
f.close()
2. Read dictionary from a binary file
import pickle
f=open('abc.dat','rb') # rb read binary file mode as rb
dic=pickle.load(f) #Read object from a pickle file or binary file
f.close()
print(dic)
3. Writing and reading integers from binary file
import pickle
f=open('numbers.dat','wb')
n=int(input("how many number you want to enter?"))
for i in range(n):
x=int(input("enter number\n"))
pickle.dump(x,f)
f.close()
f=open('numbers.dat','rb')
for i in range(n):
y=pickle.load(f) #Read object from a pickle file or binary file
print(y)
f.close()
4. Writing List in binary file
import pickle
list=[1,2,3,4,5,6,7,8,9,10]
f=open('abc.dat','wb')
pickle.dump(list,f) # dump list into f
f.close()
5. Write employee name and salary into binary file
import pickle
f=open('emp.dat','wb')
n=int(input("Enter no of employees\n"))
d={}
i=1
while i<=n:
name=input("Enter name")
salary=int(input("Enter salary"))
d[name]=salary
i=i+1
pickle.dump(d,f) # dump d into f
f.close()
6. Reading employ name and salary where salary greater then 4000 from binary file emp.dat
import pickle
f=open("emp.dat","rb")
rd=pickle.load(f)
for key,value in rd.items():
if(value>4000):
print(key,":",value)
7.Display name of employees where salary greater then 10000 from binary file emp.dat
import pickle
f=open("emp.dat","rb")
rd=pickle.load(f)
for key,value in rd.items():
if(value>4000):
print(key)
MCQ
Which of the following commands is used to open a file “c:\temp.txt” in append-mode?
a. outfile - open(“c:/temp.txt”, “a”)
b. outfile - open(“c:\\temp.txt”, “rw”)
c. outfile - open(“c:\temp.txt”, “w+”)
d. outfile - open(“c:\\temp.txt”, “r+”)
What are the binary files used for?
a. It is used to store data in the form of bytes.
b. To store data
c. To look folder good
d. None of these
What is the function of `rb` mode in binary?
a. Both reading and writing operations can take place.
b. File is in only write mode.
c. File is created if it does not exist.
d. File must exist otherwise error will be shown.
What is the description of `r+b` in binary mode?
a. read and write
b. write and read
c. read only
d. none of these
What is binary file mode for append?
a. `rb` b. `wb` c. `ab` d. None of these
What is the binary file mode associated with “ file must exist, otherwise error will be raised and reading and writing can take place”.
a. read and write
b. write and read
c. read only
d. append
What is the process of converting a byte stream back to the original structure called?
a. append b. txt.file c. Unpickling d. None of these.
Which module is used to store data into python objects with their structure?
a. pickle b. binary files c. unpickle d. None of these
What is pickle.dump()?
a. dump() function is used to store the object data to the file.
b. It is used to read
c. append
d. None of these
Which one of the following is the correct statement?
a. pickle import b. import - pickle
c. import pickle d. None of the above
Which is the valid syntax to write an object onto a binary file opened in the write mode?
a. pickle.dump(<object to be written>, <file handle of open file>)
b. pickle.dump(<file handle of open file>, <object to be written>)
c. dump.pickle(<object>, <file handle>)
d. None of the above
Which method is used for object serialization?
a. Pickling b. Unpickling c. None of the above
d. All of the above
Which method of pickle module is used to read from a binary file?
a. dump() b. load() c. All of the above
d. None of the above
Which method is used for object deserialization?
a. Pickling b. Unpickling c. All of the above
d. None of the above
Which of the following is the correct syntax to read from a file using load function?
a. pickle.load(<filehandle>)
b. <object> - load.pickle(<filehandle>)
c. <object> - pickle.load(<filehandle>)
d. All of the above
Which method of pickle module is used to write onto a binary file?
a. dump() b. load() c. All of the above
d. None of the above
Which of the following file modes open a file for reading and writing both in the binary file?
a. r b. rb c. rwb d. rb+
Which of the following file modes that opens a file for reading and writing both and overwrites the existing file if the file exists otherwise creates a new file ?
a. w b. wb+ c. rwb d. rb
Which of the following file modes opens a file for appending and reading in a binary file and moves the files pointer at the end of the file if the file already exists or creates a new file?
a. .a b. .a+ c. .ab+ d. .ab
Which of the following file modes will not delete the existing data in binary file?
a. .wb b. .w c. .a d. .ab
Create a binary file student.dat to hold students’ records like Rollno., Students name, and Address using the list. Write functions to write data, read them, and print on the screen.
import pickle
rec=[]
def file_create():
f=open("student.dat","wb")
rno = int(input("Enter Student No:"))
sname = input("Enter Student Name:")
address = input("Enter Address:")
rec=[rno,sname,address]
pickle.dump(rec,f)
def read_read():
f = open("student.dat","rb")
print("*"*78)
print("Data stored in File....")
rec=pickle.load(f)
for i in rec:
print(i)
file_create()
read_data()
Write a program to store customer data into a binary file cust.dat using a dictionary and print them on screen after reading them. The customer data contains ID as key, and name, city as values.
import pickle
def bin2dict():
f = open("cust.dat","wb")
d = {'C0001':['Subham','Ahmedabad'],
'C0002':['Bhavin','Anand'],
'C0003':['Chintu','Baroda']}
pickle.dump(d,f)
f.close()
f = open("cust.dat","rb")
d = pickle.load(f)
print(d)
f.close()
bin2dict()
Insert record
Search Record
Update Record
Display record
Exit
The sales.dat binary file data contains salesID, name and city
import pickle
import os
def main_menu():
print("1. Insert a record")
print("2. Search a record")
print("3. Update a record")
print("4. Display a record")
print("5. Delete a record")
print("6. Exit")
ch = int(input("Enter your choice:"))
if ch==1:
insert_rec()
elif ch==2:
search_rec()
elif ch==3:
update_rec()
elif ch==4:
display_rec()
elif ch==5:
delete_rec()
elif ch==6:
print("Have a nice day!")
else:
print("Invalid Choice.")
def insert_rec():
f = open("sales.dat","ab")
c = 'yes'
while True:
sales_id=int(input("Enter ID:"))
name=input("Enter Name:")
city=input("Enter City:")
d = {"SalesId":sales_id,"Name":name,"City":city}
pickle.dump(d,f)
print("Record Inserted.")
print("Want to insert more records, Type yes:")
c = input()
c = c.lower()
if c not in 'yes':
break
main_menu()
f.close()
def display_rec():
f = open("sales.dat","rb")
try:
while True:
d = pickle.load(f)
print(d)
except Exception:
f.close()
main_menu()
def search_rec():
f = open("sales.dat","rb")
s=int(input("Enter id to search:"))
f1 = 0
try:
while True:
d = pickle.load(f)
if d["SalesId"]==s:
f1=1
print(d)
break
except Exception:
f.close()
if f1==0:
print("Record not found...")
else:
print("Record found...")
main_menu()
def update_rec():
f1 = open("sales.dat","rb")
f2 = open("temp.dat","wb")
s=int(input("Enter id to update:"))
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%
[1] The _________ files are used to store large data such as images, video files, audio files etc.
–> Binary
[2] The process of converting the structure to a byte stream before writing to the file is known as _________.
–> Pickling
[3] The process of converting byte stream back to the original structure is known as _______.
–> Unpickling
[4]A ______ module is used to store data into an python objects with their structure.
–> pickle
[5]A _______ function of pickle module is used to write data into binary as well as a ____________ function of pickle module is used to read data from binary file.
–> dump(), load()
[6]The _____ file mode is used to handle binary file for reading.
–> rb
[7] The _____ file mode is used when user want to write data into binary file.
–> wb
[8] A ab file mode is used to _______ in binary file format.
–> appending
The next section of Important QnA binary files CS Class 12 will provides MCQ type questions.
[1] Which of the following is not a correct statement for binary files?
a) Easy for carrying data into buffer
b) Much faster than other file systems
c) Characters translation is not required
d) Every line ends with new line character ‘\n’
[2] Which of the following file mode open a file for reading and writing both in the binary file?
a) r
b) rb
c) rb+
d) rwb
[3] Which of the following file mode opens a file for reading and writing both as well as overwrite the existing file if the file exists otherwise creates a new file?
a) w
b) wb+
c) wb
d) rwb
[4] Which of the following file mode opens a file for append or read a binary file and moves the files pointer at the end of the file if the file already exist otherwise create a new file?
a) a
b) ab
c) ab+
d) a+
[5] Ms. Suman is working on a binary file and wants to write data from a list to a binary file. Consider list object as l1, binary file suman_list.dat, and file object as f. Which of the following can be the correct statement for her?
a) f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b) f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c) f = open(‘sum_list’,’wb’); pickle.load(l1,f)
d) f = open(‘sum_list’,’rb’); l1=pickle.load(f)
[6] Which option will be correct for reading file for suman from q-5?
–> Option ) f = open(‘sum_list’,’rb’); l1=pickle.load(f)
[7] In which of the file mode existing data will be intact in binary file?
a) ab
b) a
c) w
d) wb
[8]Which one of the following is correct statement?
a) import – pickle
b) pickle import
c) import pickle
d) All of the above