0% found this document useful (0 votes)
9 views

Binary files notes2

The document provides an introduction to binary files in Python, explaining the use of the Pickle module for serializing and deserializing Python objects. It details the processes of pickling and unpickling, along with examples of writing and reading data from binary files using the dump() and load() methods. Additionally, it covers error handling for EOFError and includes programs for managing student records using dictionaries.

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Binary files notes2

The document provides an introduction to binary files in Python, explaining the use of the Pickle module for serializing and deserializing Python objects. It details the processes of pickling and unpickling, along with examples of writing and reading data from binary files using the dump() and load() methods. Additionally, it covers error handling for EOFError and includes programs for managing student records using dictionaries.

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

INTRODUCTION TO BINARY FILES

 Python considers everything as an object. So, all data types


including list, tuple, dictionary, etc. are also considered as objects.
 Suppose you are playing a video game, and 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.
 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 pickle module deals with binary files.

BINARY FILES:
 A Binary file stores the information in the form of a
stream of bytes.

 In Binary file there is no delimiter for a line.

 The file contents returned by a binary file is raw i.e. with


no translation, thus Binary files are faster than text files.

Python objects (list, dictionary etc.) have a specific structure


which must be maintained while storing or accessing them.
Python provides a special module called pickle module for this.
PICKLING refers to the process of converting the structure
(list/dictionary) to a byte stream before writing it to a file.

UNPICKLING is used to convert the byte stream back to the


original structure while reading the contents of the file.

Before reading or writing to a file, we have to import the pickle

module.

import pickle

pickle module has two main methods: dump() and load()

pickle.dump() – This method is used to write the object in the file


which is opened in ‘wb’ or ‘ab’ i.e. write binary or append binary
access mode respectively.

Syntax: pickle.dump(<structure>,<FileObject>)

Here, Structure can be list or dictionary. File Object is the file handle
of file in which we have to write.

# Simple program to write a list data into a binary file

import pickle
f=open("bina.dat","wb")
l=['Ram',99,'city']
pickle.dump(l,f)
f.close()

pickle.load() – This method is used to read data from a file and return
back into the structure (list/dictionary).

Syntax : <structure> = pickle.load(<FileObject>)

Structure can be any sequence in Python such as list, dictionary


etc. File Object is the file handle of file in which we have to write.
# Program to read data from a binary file
import pickle
f=open("bina.dat","rb")
l=pickle.load(f)
print(l)
f.close()

# Simple program to write a dictionary data into a binary file and


read data from the same file.

import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()

f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()

Note:
The pickle.load() function would raise EOFError( a run time
exception) when you reach EOF while reading from the file .You can
handle this by following one of the below given two methods
1. Using try and except blocks
2. Using with statement

Using try and except block- you must write pickle.load()enclosed in


try and except block. The try and except block together, can handle
runtime exceptions,
In the try block you write the code that can generate an exception
and in the except block, you write what to do when the exception
(EOF end of file) has occurred.
The with statement is a compact statement which combines the
opening of file and processing of file along with inbuilt exception
handling. You need not mention any exception with the with
statement.

Program to append student record to file s.dat using dictionary.

import pickle
stu={ }
f=open('s.dat','wb')
while True:
roll=int(input("Enter Roll Number: "))
name=input("Enter Name: ")
marks=float(input("Enter Marks: "))

stu['Roll_no']=roll
stu['Name']=name
stu['Marks']=marks

pickle.dump(stu,f)
ch =input("Do you want to add more record?(y/n): ")
if ch.lower()=='n':
break
print("Student records added successfully.")
f.close()

Program to open file s.dat created above, reading the objects written
in it and display them.

import pickle
f=open('s.dat','rb')
try:
while True:
data=pickle.load(f)
print(data)
except EOFError:
pass
f.close()
Create a binary file of student with roll number, name and marks.
Search for a particular record, update the student record

and display them using dictionary.

import pickle

def Write():
f=open("stu.dat","wb")
d={}
while True:
rno = int(input("Enter student RollNo:"))
nam = input("Enter student Name :")
marks=int(input("Enter student marks:"))
d['Roll_No.']=rno
d['Name']=nam
d['Marks']=marks
pickle.dump(d,f)
ch=input("Want to add more record?(y/n):")
if ch.lower()=='n':
break
f.close()

def Read():
f=open("stu.dat","rb")
try:
while True:
data=pickle.load(f)
print(data)
except:
f.close()

def Search():
f=open('stu.dat','rb')
rno = int(input("Enter rollno.to be search: "))
found=0
try:
while True:
data=pickle.load(f)
if data['Roll_No.']==rno:
print(data)
found=1
break
except EOFError:
f.close()
if found==0:
print("No record found")

def Update():
f=open('stu.dat','rb+')
rno=int(input("Enter rollno to be updated:"))
found=0
try:
while True:
pos = f.tell() # Store the current position
data = pickle.load(f)
if data['Roll_No.'] == rno:
data['Marks'] = int(input("Enter updated marks: "))
f.seek(pos) # Move the file pointer back to the start of the
record
pickle.dump(data, f) # Update the record
found = 1
break # Exit after updating the record

except EOFError:
pass # Reached the end of the file

f.close()

if found == 0:
print("No record found")

Write()
Read()
Search()
Update()
Read()

Output:

Enter student RollNo:1


Enter student Name :ram
Enter student marks:99
Want to add more record?(y/n):y
Enter student RollNo:2
Enter student Name :tina
Enter student marks:67
Want to add more record?(y/n):y
Enter student RollNo:3
Enter student Name :demo
Enter student marks:78
Want to add more record?(y/n):n
{'Roll_No.': 1, 'Name': 'ram', 'Marks': 99}
{'Roll_No.': 2, 'Name': 'tina', 'Marks': 67}
{'Roll_No.': 3, 'Name': 'demo', 'Marks': 78}
Enter rollno.to be search: 2
{'Roll_No.': 2, 'Name': 'tina', 'Marks': 67}
Enter rollno to be updated:1
Enter updated marks: 100
{'Roll_No.': 1, 'Name': 'ram', 'Marks': 100}
{'Roll_No.': 2, 'Name': 'tina', 'Marks': 67}
{'Roll_No.': 3, 'Name': 'demo', 'Marks': 78}

You might also like