Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views25 pages

File-Handling (Binary File) Class 12

all you need to know about binary files (class 12)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

File-Handling (Binary File) Class 12

all you need to know about binary files (class 12)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

As Per CBSE Computer Science

Syllabus
2025-26

Chapter-3

BINARY FILE
BINARY FILE

Binary files are also stored in terms of bytes (0s and 1s), but unlike
text files, these bytes do not represent the ASCII values of characters.
Rather, they represent the actual content such as image, audio, video,
compressed versions of other files, executable files, etc. These files
are not human readable. Thus, trying to open a binary file using a text
editor will show some garbage values. We need specific software to
read or write the contents of a binary file.

Binary files are stored in a computer in a sequence of bytes. Even a


the file

single bit change can corrupt the file and make it unreadable to the
supporting application
Pickle Module

Suppose you are playing a video game, and after some time, you want to close it. So, the program
should
be able to store the current state of the game, including current level/stage, your score, etc. as a
Python object. Likewise, you may like to store a Python dictionary as an object, to be able to retrieve
later.
To save any object structure along with data, Python provides a module called Pickle.
The module Pickle is used for serializing and de-serializing any Python object structure.

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.
De-serialization or unpickling is the inverse of pickling process where a byte stream is
converted back to Python object.
the file
The pickle module deals with binary files. Here, data are not written but dumped and similarly, data are
not read but loaded. The Pickle Module must be imported to load and dump data.

The pickle module provides two methods - dump() and load() to work with binary files for
pickling and unpickling, respectively.
Binary File Handling
Binary files can store more structed python objects like list, tuple, dictionary by converting these objects
into byte stream( called serialization/pickling), these objects can brought back to original form while
reading the file (called unpickling).

Pickle module is very useful when it come to binary file handling. We will use dump() and load()
methods of pickle module to write and read data objects into binary files.

Writing into a binary file:


The dump() function of pickle module can be used to write an object into a binary file.
Syntax: pickle.dump( <object_to_be_witten>, <filehandle>)
Ex: Import the pickle module to use
import pickle dump() method
f=open(‘csSubjects.dat’, ’wb’) Mode need to be ‘wb’, specifying
tup1=(“AI”,”Networking”,”DBMS”,”Python”) write operation on binary file
Pickle.dump(tup1,f) dump() method writes the tuple
f.close() tup1 into the file referenced by
file handle
Reading a binary file
To read from a binary file the load() method of the pickle module can be used. This method
unpickles the data from the binary file(convert binary stream into original object structure).
Syntax: <object>=pickle.load(<filehandle>)
import pickle
f=open(‘cs.dat’,’wb’)
d={“name”:”amit”,”roll”:20,”mark”:320}
pickle.dump(d,f)

header=Pickle.load(f)
Reading from binary file using load() method
sdata=pickle.load(f)
print(”Name:”,sdata[name])
print(”Roll No:”,sdata[roll])
print(”Mark:”,sdata[mark])
f.close()
Writing into Binary File (Example Program )

#program to write details(name, rollno, mark) of n number of students into a binary file

import pickle
f=open(“C:\\myfolder\\students.dat”,”wb”)
n=int(input(“Enter how many students details you want to enter”))
for i in range(n):
name=input(“Enter students name:”)
roll=int(input(“Enter students Roll No:”))
mark=int(input(“Enter students Mark:”))
data={“Name”:name,”RollNo”:roll,”Mark”:mark}
f.dump(data,f)
print(“Details of ”,n,” number of students saved successfully”)
f.close()
Reading from Binary File (Example Program )

#Program to read the details of all students in the binary file Students.dat created in the last example
import pickle
f=open(“C:\\myfolder\\students.dat”,”rb”)
print(“*******Students Details*********”)
while True:
try:
data=pickle.load(f)
print(“Name:”,data[”Name”])
print(“Roll Number:”,data[”RollNo”])
print(“Mark:”,data[”Mark”])
except EOFError:
print(“Reached end of the file”)
break
f.close()
Performing Search operation on a Binary File (Example Program )

#Program to search the details of students based on students Roll Number


import pickle
f=open(“C:\\myfolder\\students.dat”,”rb”)
sroll=int(input(“Enter the Roll Number of the student”))
found=False
print(“*******Student Details*********”)
while True:
try:
data=pickle.load(f)
if data[“RollNo”]==sroll:
found=True
print(“Name:”,data[“Name”])
print(“Roll Number:”,data[”RollNo”])
print(“Mark:”,data[“Mark”])
except EOFError:
break
If found==False:
print(“Data not found”)
f.close()
Append into a Binary File (Example Program )

#Program to append details of a new student into the binary file Student.dat

import pickle
f=open(“C:\\myfolder\\students.dat”,”ab”)
name=input(“Enter students name:”)
roll=int(input(“Enter students Roll No:”))
mark=int(input(“Enter students Mark:”))
data={“Name”:name,”RollNo”:roll,”Mark”:mark}
f.dump(data,f)
f.close()
Update a Binary File (Example Program )
#Program to update mark of a student in the the binary file Student.dat
import pickle
f=open(`C:\\myfolder\\students.dat’,`rb’)
alldata=[]
sroll=int(input(`Enter the Roll Number of the student:’))
newmark=int(input(`Enter the Mark to be updated: ‘))
while True:
try:
sdata=pickle.load(f)
alldata.append(sdata)
except EOFError:
break
f.close()
for record in alldata:
if record[`RollNo’]==sroll:
record[`Mark’]=newMark
f=open(`C:\\myfolder\\students.dat’,`rb’)
for record in alldata:
pickle.dump(record)
f.close()
import pickle
def addrec():
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
bfile.close()
break
Reading the employee records

def readrec():
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
bfile.close()
Menu Driven Program for binary file add,update,view,search remove operations on it

Writing and reading in a binary file


import pickle
import os
def addrec():
f = open("try.dat","wb")
ans = "y"
while ans=="y":
r = int(input("Enter a roll no : "))
name = input("Enter a name : ")
total = int(input("Enter your total : "))
l = [r,name,total]
pickle.dump(l,f)
ans = input("Add more record (y/n) : ")
f.close()
def viewall():
f=open("try.dat","rb")
try:
while True:
x=pickle.load(f)
print(x[0],x[1],x[2])
except EOFError:
f.close()
def modify():
f=open("try.dat","rb")
f1=open("temp.dat","wb")
flag=0
try:
while True:
x=pickle.load(f)
if x[2]>=350 and x[2]<=450:
x[2]+=10
pickle.dump(x,f1)
flag=1
else: pickle.dump(x,f1)
except EOFError:
f.close() ; f1.close()
os.remove("try.dat")
os.rename("temp.dat","try.dat")
if flag==0: print("No record found")
else: print("records are updated for the total range between 350-450")
def modify1():
f=open("try.dat","rb")

try:
flag = 0
while True:
x1 = f.tell()
x=pickle.load(f)
if x[2]>=350 and x[2]<=450:
x[2]+=10
f.seek(x1)
pickle.dump(x,f1)
flag = 1

except EOFError:
f.close()
if flag==0 :
print(" no matching record found.")
def Del():
f=open("try.dat","rb")
f1=open("temp.dat","wb")
n = int(input(" enter the roll number:"))
flag =0
try:
while True:
x=pickle.load(f)
if x[0]==n :
flag=1
else:
pickle.dump(x,f1)
except EOFError:
f.close()
f1.close()
if flag==0:
print("No record found")
else:print("record deleted")
os.remove("try.dat")
os.rename("temp.dat","try.dat")
def view_check():
f = open("try.dat","rb")
flag = 0
ll = int(input("ENTER LOWER LIMIT"))
ul = int(input("ENTER UPPER LIMIT:"))
print("roll.no\tName\tTotal")
try:
while True:
x = pickle.load(f)
if x[2] >= ll and x[2] <= ul:
print(x[0],"\t",x[1],"\t",x[2])
flag = 1
else: pass
except EOFError:
f.close()
if flag == 0:
print("RECORD NOT FOUND")
def search():
f = open("try.dat","rb")
flag = 0
n= int(input("ENTER THE ROLL NUMBER TO BE SEARCHED:"))

try:
while True:
x = pickle.load(f)
if x[0] == n :
print(x)
flag = 1
else:
pass
except EOFError:
f.close()
if flag == 0:
print("RECORD NOT FOUND")
print('''\t\t\t MAIN MENU
1.ADD RECORD
2.UPDATE RECORD
3.DELETE RECORD
4.VIEW ALL
5.SEARCH A RECORD
6.VIEW A RANGE OF RECORD
7.EXIT''')
while True:
ch = int(input("ENTER YOUR CHOICE:"))
if ch == 1:
addrec()
elif ch == 2:
modify()
elif ch == 3:
Del()
elif ch == 4:
viewall()
elif ch == 5:
search()
elif ch == 6:
view_check()
elif ch == 7:
print("END")
break
else:
print("ENTER A CHOICE BETWEEN 1 TO 7")
Board Question
Board Question solution
Board Question solution
Board Question solution

You might also like