0% found this document useful (0 votes)
13 views31 pages

Binary Files

A binary file contains non-text computer-readable data like images, videos, and audio. It is smaller in size than an equivalent text file, allowing for faster storage, transmission, and processing. Python can be used to create, read, append, search, and modify binary files using the pickle and OS modules. Data is serialized into the binary file using pickle.dump() and deserialized using pickle.load(). The 'b' mode is used for binary files.
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)
13 views31 pages

Binary Files

A binary file contains non-text computer-readable data like images, videos, and audio. It is smaller in size than an equivalent text file, allowing for faster storage, transmission, and processing. Python can be used to create, read, append, search, and modify binary files using the pickle and OS modules. Data is serialized into the binary file using pickle.dump() and deserialized using pickle.load(). The 'b' mode is used for binary files.
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/ 31

Binary Files

Introduction
• A binary file is a computer file that is not a text
file.
• The term "binary file" is often used as a term
meaning "non-text file“
• A binary file is computer-readable but not
human-readable.
• A binary file is a file stored in binary format.
Use of Binary Files

• A binary file is usually very much smaller than a


text file that contains an equivalent amount of
data.

• For image, video, and audio data this is


important. Small files save storage space, can be
transmitted faster, and are processed faster.
Binary File Operations 4

• Create a Binary File


• Read record from binary file
• Append record in Binary File
• Read Multiple Records in Binary File
• Delete a record in a Binary File
• Update a record in Binary File
Packages Required 5

• pickle – Pickle module is used to serialize data


into binary format
– dump() - function to write data in binary file
– load() – read data from binary file
• OS – Os module provide common functions to
manage the files and directories
– remove() – remove a file from disk
– rename() – rename a file on the disk i.e. rename old
filename with new filename.
rename(“oldfilename”,”newfilename”)
Create a Binary File 6

Method :1.1 (sentence form)

mode ‘b’ is compulsory to


import pickle
perform with binary files

file = open('student.dat', 'wb')


pickle.dump(“this is the file content”,file)
file.close()

print('Binary file Generated...')


Create a Binary File 7

Method :1.2 (sentence form)

import pickle

student = [‘ram is a good boy’,’rita is a good girl’]

file = open('student.dat', 'wb')


pickle.dump(student,file)
file.close()
mode ‘b’ is compulsory to
print('Binary file Generated...') perform with binary files
Create a Binary File 8

Method :2(nested list form)

import pickle

student = [[1,”reena”,56],[2,”teena”,76]]

file = open('student.dat', 'wb')


pickle.dump(student,file)
file.close()
mode ‘b’ is compulsory to
print('Binary file Generated...') perform with binary files
Create a Binary File 9

Method :3(take entry from user and can add multiple records in a file)

import pickle

name = input('Enter name :')


roll = int(input('Enter roll :'))

student = [name,roll]

file = open('student.dat', 'wb') mode ‘b’ is compulsory to


pickle.dump(student,file) perform with binary files
file.close()

print('Binary file Generated...')

Enter name :reena


Enter roll :10
Binary file Generated...
Create a Binary File 10

Method :4(take entry from user and append in a list,i.e. add single record at a time

import pickle
name = input('Enter name :')
roll = int(input('Enter roll :'))
s = [name,roll]
student=[]
student.append(s)
file = open('student.dat', 'wb') mode ‘b’ is compulsory to
perform with binary files
pickle.dump(student,file)
file.close()
Enter name :reena
print('Binary file Generated...') Enter roll :10
Binary file Generated...
Read Data from Binary File 11

Method :1(to read one record at a time)

import pickle
file = open('student.dat', 'rb') ‘rb’ stand for reading
data = pickle.load(file) mode + binary file
print(data)
file.close()
Read Data from Binary File 12

Method :2.1(to read 3 records)

import pickle
file = open('student.dat', 'rb') ‘rb’ stand for reading
mode + binary file
data = pickle.load(file)
r = pickle.load(file)
y = pickle.load(file)
print(data)
print(r)
print(y)
file.close()
Read Data from Binary File 13

Method :2.2 (to read 3 records using for loop)

import pickle
file = open('student.dat', 'rb') ‘rb’ stand for reading
mode + binary file
for i in range(3):
data = pickle.load(file)
print(data)
file.close()
OR

import pickle
file = open('student.dat', 'rb')
for i in range(3):
for J in pickle.load(f):
print(J)
file.close()
Read Multiple Record from Binary File 14

Method :3(display all records)


import pickle
file = open('student.dat', 'rb')
while True:
try:
data = pickle.load(file)
print(data)
except:
break
file.close()
Read from Binary File 15

Method :4(display selective records postion wise )

import pickle
name = input('Enter name :')
roll = int(input('Enter roll :')) If records
student = [name,roll] are stored
file = open('student.dat', 'wb') in a list
pickle.dump(student,file) then to
file.close() display its
print('Binary file Generated...') content
Append Data in Binary File using List Concept 16

Method :1

import pickle
name = input('Enter name :')
roll = int(input('Enter roll :'))
student=[name,roll]
file = open('student.dat', 'ab')
pickle.dump(student, file)
‘ab’ stand for
file.close()
appending mode
print('Binary file appended...') in binary file

Enter name :sheena


Enter roll :20
Binary file appended...
Add/Append Data in Binary File using List Concept 17

Method :2 using for loop

import pickle
N=int(input(“enter how many records u want to enter”))
file = open('student.dat', 'ab')
for i in range(N):
name = input('Enter name :')
roll = int(input('Enter roll :'))
student=[name,roll]
‘ab’ stand for
pickle.dump(student, file) appending mode
file.close() in binary file
print('Binary file appended...')

enter how many records u want to enter2


Enter name :sheena
Enter roll :20
Enter name :heena
Enter roll :10
Binary file appended...
Add/Append Data in Binary File using List Concept 18

Method :2 using while loop

import pickle
file = open('student.dat', 'ab')
while True: ‘ab’ stand for
name = input('Enter name :') appending mode
roll = int(input('Enter roll :')) in binary file
student=[name,roll]
pickle.dump(student, file)
ch=input(“More records")
if(ch=='n' or ch=='N'): Enter name :sheena
break Enter roll :20
file.close() More records y
print('Binary file appended...') Enter name :heena
Enter roll :10
More records n
Binary file appended...
Search Data in Binary File 19

import pickle
n = input('Enter name to search :')
file1 = open('student.dat', 'rb')

while True:
try:
data = pickle.load(file1)
if data[0]==n:
print(data)
except:
break

file1.close()
Modify/Update a Record 20

1. Two Files required


2. OS module required
3. Read a Name of student that you want to delete in a temporary variable
4. Open first file in read mode
5. Open Temporary file in writing mode
6. read first record and save data in a record variable
7. compare temporary name with the name stored in record variable
8. if record match then read new values in this record variable
9. Write your record in Temporary file
10. repeat this process till end of file
11. close both files
12. remove original file
13. rename temporary file as your original file
Update Record 21

Method :1 (change a single entry in a record) # write the file content


f=open(“student.dat","wb")
import pickle v=[[1,"ayaan",35],[2,"ajay",76]]
import os pickle.dump(v,f)
f.close()
file1 = open(‘student.dat', 'rb')
file2 = open('temp.dat', 'wb')
data = pickle.load(file1)
d=[]
for i in data:
if i[1]==“ayaan”:
i[2]=65 # or i[2] = input('Enter new marks')
d.append(i)
else:
d.append(i)
#To display the file content
pickle.dump(d,file2)
f=open(“student.dat","rb")
file1.close()
g=pickle.load(f)
file2.close()
print(g)
os.remove('student.dat')
os.rename('temp.dat', ‘student.dat')
print('Record updated...')
Update Record 22

Method :2 (change entire record) #file content


f=open(“student.dat","wb")
import pickle v=[[1,"ayaan",35],[2,"ajay",76]]
import os pickle.dump(v,f)
d=[] f.close()
file1 = open(‘student.dat', 'rb')
file2 = open('temp.dat', 'wb')
data = pickle.load(file1)
for i in data:
if i[0]==1:
d.append([3,"siddharth",97])
else:
d.append(i)
pickle.dump(d,file2)
file1.close()
#to display the file content
file2.close()
f=open(“student.dat","rb")
os.remove('student.dat')
g=pickle.load(f)
os.rename('temp.dat', ‘student.dat')
print(g)
print('Record updated...')
Update records 23

Method :4
To modify the record
x=False
f=open("aa.dat","rb")
f1=open("temp.dat","wb")
dispr()
a=int(input("enter product no which we want to update:"))
while True:
try:
s=pickle.load(f)
if a==s[0]:
print("current name",s[1])
s[1]=input("enter name")
s[2]=float(input("enter price"))
pickle.dump(s,f1)
x=True
else:
pickle.dump(s,f1)
except:
break
if(x==False):
print("record not found")

f.close()
f1.close()
os.remove("aa.dat")
os.rename("temp.dat","aa.dat")

f2=open("aa.dat","rb")
while True:
try:
s=pickle.load(f)
print(s)
except:
break
f2.close()
Delete a Record 24

1. Two Files required


2. OS module required
3. Read Name of student that you want to delete
4. Open first file in read mode
5. Open Temporary file in writing mode
6. read first record and save data in a record variable
7. compare the name with the name stored in record variable
8. if record matches than do not write the same record in temporary file
and read next record
9. if record does not match then write this record in temporary file and
then read the next record.
10. repeat this process till end of file
11. close both files
12. remove original file
13. rename temporary file as your original file
Delete Record 25

import pickle
import os

n = input('Enter name to delete :')

file1 = open('student.dat', 'rb')


file2 = open('temp.dat', 'wb')

while True:
try:
data = pickle.load(file1)
if data[1]!= n: Enter name to delete :reena
pickle.dump(data,file2) Record deleted...
except:
break
file1.close()
file2.close()
os.remove('student.dat')
os.rename('temp.dat', 'student.dat')
print('Record deleted...')
Create a Binary File using Dictionary concept 26

import pickle

name = input('Enter name :')


roll = int(input('Enter roll :'))

student = {'name': name, 'roll': roll}

file = open('student.dat', 'wb') mode ‘b’ is compulsory to


pickle.dump(student,file) perform with binary files
file.close()

print('Binary file Generated...')

Enter name :reena


Enter roll :10
Binary file Generated...
Read Data from Binary File using dictionary concept 27

Method :1(to read one record at a time)

import pickle
file = open('student.dat', 'rb') ‘rb’ stand for reading
data = pickle.load(file) mode + binary file
print(data)
file.close()
import pickle
name = input('Enter name :')
roll = int(input('Enter roll :'))
student = {'name': name, 'roll': roll}
file = open('student.dat', 'wb')
{'name': 'reena', 'roll': '10'}
pickle.dump(student,file)
file.close()
print('Binary file Generated...')
Append Data in Binary File using Dictionary concept 28

import pickle
name = input('Enter name :')
roll = int(input('Enter roll :'))
student = {'name': name, 'roll': roll}
file = open('student.dat', 'ab')
pickle.dump(student, file)
‘ab’ stand for
file.close() appending mode
print('Binary file appended...') in binary file

Enter name :sheena


Enter roll :20
Binary file appended...
Search Data in Binary File using Dictionary concept 29

import pickle
n = input('Enter name to search :')
file1 = open('student.dat', 'rb')

while True:
try:
data = pickle.load(file1)
if n == data['name']:
print(data)
except:
break

file1.close()
Update Record using Dictionary Concept 30

import pickle
import os

n = input('Enter name to delete :')


file1 = open('student.dat', 'rb')
file2 = open('temp.dat', 'wb')
while True:
try:
data = pickle.load(file1)
if n == data['name']:
data['name'] = input('Enter new name')
pickle.dump(data,file2)
except:
break
file1.close()
file2.close()
os.remove('student.dat')
os.rename('temp.dat', 'student.dat')
print('Record deleted...')
Delete Record using Dictionary concept 31

import pickle
import os

n = input('Enter name to delete :')

file1 = open('student.dat', 'rb')


file2 = open('temp.dat', 'wb')

while True:
try:
data = pickle.load(file1)
if n != data['name']: Enter name to delete :reena
pickle.dump(data,file2) Record deleted...
except:
break
file1.close()
file2.close()
os.remove('student.dat')
os.rename('temp.dat', 'student.dat')
print('Record deleted...')

You might also like