Table of Contents

Working with Binary Files in Python

Example Description
Discover the world of binary file handling in Python through a comprehensive tutorial. Learn how to perform essential operations on binary files using the pickle module, including data writing and reading. Dive into practical examples and enhance your Python programming skills today.

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:

  1. Display “WORKING WITH BINARY FILES” to set the context for the code.
  2. Open a file named “empfile.dat” in binary append mode (“ab”) and assign the file object to bfile.
  3. Initialize recno as 1 to keep track of the record number.
  4. Display the current record number (recno).
  5. Prompt the user to input employee data, including employee number, name, basic salary, and allowances.
  6. Calculate the total salary as the sum of basic salary and allowances.
  7. Create a list named edata containing the employee data.
  8. Use the pickle.dump() function to serialize and write edata to the binary file.
  9. Prompt the user whether they want to enter more records. If the answer is ‘n’, exit the loop.
  10. Retrieve the size of the binary file using the tell() method and print it.
  11. Close the binary file using the close() method.
  12. Begin reading the employee records from the binary file using the load() function of the pickle module
  13. Open the “empfile.dat” file in binary read mode (“rb”)
  14. Load data from the file using pickle.load() and assign it to edata.
  15. Print the record number (readrec) and the loaded employee data.
  16. Increment readrec by 1.
  17. Handle the EOFError exception to stop reading when all records have been read.
  18. 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]