PYTHON-Programs_Binary-File-Handling
PYTHON-Programs_Binary-File-Handling
# If print as a separate character, then the character code will be displayed - as an integer
print("d[5] = ", d[5]) # d[5] = 40
print("d[0] = ", d[0]) # d[0] = 128
# 2. File writing
# 2.1. Open file for writing
f = open('myfile3.bin', 'wb')
# 1. Given set
M = { 0.2, 0.3, 0.8, 1.2, 1.77 }
# 3.3.2. Loop of reading the lines and the creation of a matrix size m2*n2
i=0
while i < m2: # m2 rows in matrix
row = [] # one row in list
j=0
while j < n2:
bs = f.readline() # read one element of type bytes
s = bs.decode() # convert bytes=>str
s = s[:-1] # remove '\n'
row += [s] # add to the list
j = j+1
MATRIX2 += [row] # add one row of the list to the matrix
i = i+1
# 3. Combine lists
L3 = L1 + L2
Deserialization or Un-pickling
Deserialization or Un-pickling is the process in which byte streams are converted back into
python objects. Deserialization produces a replica of the original object.
dump() Method
The dump() method converts the python objects into byte streams and writes them
immediately into a binary file.
Syntax of dump() method
pickle.dump(obj, file)
Example
import pickle
# store roll and name of 5 students in a binary file record.txt
with open(r'D:\record.txt', 'ab+') as fileobj:
# write the object data into binary file using the dump() method
pickle.dump(data, fileobj)
load() Method
The load() method reads the byte stream of one or more python objects from a binary file
and reconstructs the replica of the original python object.
Syntax of load() method
obj = pickle.load(file)
Example
import pickle
# read all the roll and name of 5 students from the binary file record.txt
with open(r'D:\record.txt', 'rb') as fileobj:
while True:
try:
# load individual student list into data using the load() method
data = pickle.load(fileobj)
print('Roll: %d' %(data[0]))
print('Name: %s' %(data[1]))
except EOFError:
break
Output
Roll: 1
Name: Allen
Roll: 2
Name: Thomas
Roll: 3
Name: David
Roll: 4
Name: William
Roll: 5
Name: Henry
dumps() Method
The dumps() method only converts the python objects into a string of bytes and return
them as byte object. This method itself does not write the byte object into a binary file. We
must use the write() method of the file object to write it into a binary file.
This method is useful when we only want the serialization result of a python object so that
we can transfer it over a network or other process.
Syntax of dumps() method
byteobj = pickle.dumps(obj)
Example
import pickle
# convert a string into string of byte and display it on the screen
data = input('Enter a string: ')
byteobj = pickle.dumps(data)
print(byteobj)
Output
Enter a string: Aeroplane
b'\x80\x04\x95\r\x00\x00\x00\x00\x00\x00\x00\x8c\tAeroplane\x94.'
loads() Method
The loads() method reads the string of bytes and reconstructs the replica of the original
python object.
Syntax of loads() method
obj = pickle.loads(byteobj)
Example
import pickle
# convert a string of bytes into a python object and display it on the screen
data = b'\x80\x04\x95\r\x00\x00\x00\x00\x00\x00\x00\x8c\tAeroplane\x94.'
print(data)
obj = pickle.loads(data)
print(obj)
Output
b'\x80\x04\x95\r\x00\x00\x00\x00\x00\x00\x00\x8c\tAeroplane\x94.'
Aeroplane
Note: The dump() and dumps() methods are used for serialization or pickling of python
objects, whereas the load() and loads() methods are used for deserialization or unpickling
of byte streams into python objects.
while True:
os.system('cls')
print('1. Add Record')
print('2. Display Records')
print('3. Search Record')
print('4. Modify Record')
print('5. Delete Record')
print('0. Exit')
choice = int(input('Enter Your Choice : '))
# Add Record
if choice == 1:
with open(r'D:\record.txt', 'ab+') as fileobj: # open file for adding records
# Display Records
elif choice == 2:
with open(r'D:\record.txt', 'rb') as fileobj: # open file for displaying records
f=0
print('\nNAME\t\t\tAGE\tSALARY') # print the heading
while True:
try:
# load individual record from the file using the load() method
data = pickle.load(fileobj)
if len(data) !=0:
f=1
print('%s\t\t\t%d\t%.2f' %(data[0], data[1], data[2]))
except EOFError:
break
if f==0:
print('\nRecord does not exist')
input('\nPress enter to continue...') # Pause the loop so that the user can see the
message
# Search Record
elif choice == 3:
with open(r'D:\record.txt', 'rb') as fileobj: # open file for searching records
f=0
nm = input('Enter name to search: ')
print('\nNAME\t\t\tAGE\tSALARY') # print the heading
while True:
try:
# load individual record from the file using the load() method
data = pickle.load(fileobj)
if nm == data[0]:
f=1
print('%s\t\t\t%d\t%.2f' %(data[0], data[1], data[2]))
break
except EOFError:
break
if f==0:
print('\nRecord does not exist')
input('\nPress enter to continue...') # Pause the loop so that the user can see the
message
# Modify Record
elif choice == 4:
records = []
f=0
nm = input('Enter name to modify record: ')
with open(r'D:\record.txt', 'rb') as fileobj: # open file for reading records
while True:
try:
# load individual record from the file using the load() method
data = pickle.load(fileobj)
if data[0] == nm:
data[0] = input('New Name: ')
data[1] = int(input('New Age: '))
data[2] = float(input('New Salary: '))
f=1
except EOFError:
break
if f==0:
print('\nRecord does not exist')
else:
input('\nPress enter to continue...') # Pause the loop so that the user can see the
message
# Delete Record
elif choice == 5:
records = []
with open(r'D:\record.txt', 'rb') as fileobj: # open file for reading records
while True:
try:
# load individual record from the file using the load() method
data = pickle.load(fileobj)
except EOFError:
break
if f==0:
print('\nRecord does not exist')
else:
print('\nRecord deleted successfully')
input('\nPress enter to continue...') # Pause the loop so that the user can see the
message
elif choice == 0:
exit(0)