Introduction:
Binary file manipulation is a key skill for programmers dealing with data storage and retrieval. In this tutorial, we delve into binary file operations in Python, showcasing how to write and read employee records. By leveraging the pickle module, you’ll explore practical examples that demonstrate data serialization and deserialization, allowing you to store and retrieve complex data structures efficiently.
Code:
# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
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
print("\tTOTAL SALARY : ", totsal)
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 ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
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:
pass
bfile.close()
Logic:
- Display “WORKING WITH BINARY FILES” to set the context for the code.
- Open a file named “empfile.dat” in binary append mode (“ab”) and assign the file object to bfile.
- Initialize recno as 1 to keep track of the record number.
- Display the current record number (recno).
- Prompt the user to input employee data, including employee number, name, basic salary, and allowances.
- Calculate the total salary as the sum of basic salary and allowances.
- Create a list named edata containing the employee data.
- Use the pickle.dump() function to serialize and write edata to the binary file.
- Prompt the user whether they want to enter more records. If the answer is ‘n’, exit the loop.
- Retrieve the size of the binary file using the tell() method and print it.
- Close the binary file using the close() method.
- Begin reading the employee records from the binary file using the load() function of the pickle module
- Open the “empfile.dat” file in binary read mode (“rb”)
- Load data from the file using pickle.load() and assign it to edata.
- Print the record number (readrec) and the loaded employee data.
- Increment readrec by 1.
- Handle the EOFError exception to stop reading when all records have been read.
- close the binary file.
Output:
>>WORKING WITH BINARY FILES
>>Enter Records of Employees
>>RECORD No. 1
>>Employee number : 2
Employee Name : shad
Basic Salary : 12000
Allowances : 1200
TOTAL SALARY : 13200>>Do you wish to enter more records (y/n)? y
>>RECORD No. 2
>>Employee number : 5
Employee Name : anand
Basic Salary : 12000
Allowances : 1300
TOTAL SALARY : 13300>>Do you wish to enter more records (y/n)? n
>>Record entry OVER
>>Size of binary file (in bytes): 241
>>Now reading the employee records from the file
>>Record Number : 1
>>[2, ‘shad’, 12000, 1200, 13200]
>>Record Number : 2
>>[5, ‘anand’, 12000, 1300, 13300]