0% found this document useful (0 votes)
50 views6 pages

Binary File Handling in Python

The document contains multiple Python programs for handling binary files, including creating, reading, updating, and searching records for toys, students, books, employees, products, and customers. Each section provides a specific function to manage data structures defined for each type of record, utilizing the pickle module for serialization. The programs demonstrate various file operations such as appending records, searching by criteria, and displaying filtered results based on specific conditions.

Uploaded by

jkdhanyaa2008
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)
50 views6 pages

Binary File Handling in Python

The document contains multiple Python programs for handling binary files, including creating, reading, updating, and searching records for toys, students, books, employees, products, and customers. Each section provides a specific function to manage data structures defined for each type of record, utilizing the pickle module for serialization. The programs demonstrate various file operations such as appending records, searching by criteria, and displaying filtered results based on specific conditions.

Uploaded by

jkdhanyaa2008
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

BINARY FILE HANDLING PROGRAMS

1. A binary file “[Link]” has structure [TID, Toy, Status,MRP].


i. Write a user defined function CreateFile() to input data for a record and add to
"[Link]"
ii. Write a function OnOffer() in Python to display the detail of those Toys, which has
status as “ON OFFER” from "[Link]" file.

import pickle
def Createfile():
fo=open("[Link]","ab")
TID=input("Enter Toy ID:")
Toy=input("Enter toy name:")
Status=input("Enter status of a toy:")
MRP=int(input("Enter MRP of a Toy:"))
rec=[TID,Toy,Status,MRP]
[Link](rec,fo)
[Link]()
Createfile()
def OnOffer():
fo=open("[Link]","rb")
S=input("Enter status of a toy to search:")
found=0
print("The detail of the Toys, which has status as “ON OFFER”")
try:
while True:
rec=[Link](fo)
if rec[2].upper()=='ON OFFER':
found=1
print(rec)
except EOFError:
if found==0:
print("No record found")
[Link]()
OnOffer()

2. A binary file “[Link]” has structure [rollno, name, marks].


i. Write a user defined function insertRec() to input data for a student and add to
[Link].
ii. Write a function searchRollNo( r ) in Python which accepts the student’s rollno as
parameter and searches the record in the file “[Link]” and shows the details of student
i.e. rollno, name and marks (if found) otherwise shows the message as ‘No record found’.

import pickle
def insertRec():
fo=open("[Link]","ab")
rollno=input("Enter rollno of a student:")
name=input("Enter name of a student:")
marks=int(input("Enter marks of a student:"))
rec=[rollno,name,marks]
[Link](rec,fo)
[Link]()
insertRec()
def searchRollNo( r):
fo=open("[Link]","rb")
found=0
print(“Student Details”)
try:
while True:
rec=[Link](fo)
if rec[0]==r:
found=1
print(rec)
except EOFError:
if found==0:
print("No record found")
[Link]()
rollno=int(input(“Enter roll no to search:”))
searchRollNo( rollno)

3. A binary file “[Link]” has structure: [BookNo, Book_Name, Author,Price].


i. Write a user defined function CreateFile() to input data for a record and add to
[Link].
ii. Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in the
binary file “[Link]”.

import pickle
def CreateFile():
fo=open("[Link]","ab")
BookNo=int(input("Enter BookNo:"))
Book_Name=input("Enter name of a book:")
Author=input("Enter author of a book:")
Price=int(input("Enter the Price of the book:"))
rec=[BookNo,Book_Name,Author,Price]
[Link](rec,fo)
[Link]()
CreateFile()

def CountRec(Author):
fo=open("[Link]","rb")
count=0
try:
while True:
rec=[Link](fo)
if rec[2]==Author:
count+=1
print(rec)
except EOFError:
[Link]()
return count
Author=input("Enter Author name to search:")
print("Total no of books in the given author:",CountRec(Author))

4. A binary file “[Link]” has structure (admission_number, Name, Percentage).


Write a function countrec() in Python that would read contents of the file
“[Link]” and display the details of those students whose percentage is above 75.
Also display number of students scoring above 75%.
import pickle
def countrec():
fo=open("[Link]","rb")
count=0
print(“Student details whose percentage > 75:”)
try:
while True:
rec=[Link](fo)
if rec[2]>75:
count+=1
print(rec)
except EOFError:
[Link]()
print(“Total no of students scored 75 % above are:”, count)
countrec():

5. Write a python program to append a new records in a binary file –“[Link]”. The
record can have Rollno, Name and Marks.
import pickle
def appendRec():
fo=open("[Link]","ab")
Rollno=input("Enter rollno of a student:")
Name=input("Enter name of a student:")
Marks=int(input("Enter marks of a student:"))
rec=[Rollno,Name,Marks]
[Link](rec,fo)
[Link]()
appendRec()

6. Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of an employee to a binary file ”[Link]‟. Each record
consists of a list with field elements as EId, EName and ESal to store Emp id, Empname
and Empsalary respectively.
(ii) search()- To display the records of the employee salary is more than 10000.

import pickle
def add():
fo=open("[Link]","ab")
EId=int(input("Enter employee ID:"))
EName=input("Enter name of an Employee:")
ESal=int(input("Enter the salary:"))
rec=[EId,EName,ESal]
[Link](rec,fo)
[Link]()
add()

def search():
fo=open("[Link] ","rb")
found=0
try:
while True:
rec=[Link](fo)
if rec[2]>10000:
found=1
print(rec)
except EOFError:
if found==0:
print(“No record found”)
[Link]()
search()

7. Write a program in python that defines and calls the following user defined functions:
Add_rating() – To read product name and rating from the user and store the same into the
binary file “[Link]”
Display() – To read the file “[Link]” and display the products where the rating is
above 10.
import pickle
def Add_rating():
fo=open("[Link]","ab")
pname=input("Enter Product Name:")
prating=int(input("Enter the Product rating:"))
rec=[pname,prating]
[Link](rec,fo)
[Link]()
Add_rating()

def Display():
fo=open("[Link] ","rb")
found=0
try:
while True:
rec=[Link](fo)
if rec[1]>10:
found=1
print(rec)
except EOFError:
if found==0:
print(“No record found”)
[Link]()
Display()

8. Write a program in python that defines and calls the following user defined functions:
(i) insertData() – To accept and add data of a customer and add it to a binary file
[Link]‟. Each record should contain a list consisting customer name, mobile no,
date of Purchase, item purchased.
(ii) frequency (name) – To accept the name of a customer and search how many times the
customer has purchased any item. The count and return the number.
import pickle
def insertData():
fo=open("[Link]","ab")
cname=input("Enter customer name:")
mobileno=int(input("Enter mobile number:"))
dop=input("Enter date of purchase:")
itempurchased= input("Enterthe item purchased:"))
rec=[cname, mobileno, dop, itempurchased]
[Link](rec,fo)
[Link]()
insertData()
def frequency(name):
fo=open("[Link] ","rb")
count=0
try:
while True:
rec=[Link](fo)
if rec[0]==name:
count+=1
except EOFError:
[Link]()
return count
cname=input("Enter customer name to search:")
print("Total no of items purchased by the given customer are:”, frequency(cname))

9. i) A binary file “[Link]” has structure (EID, Ename, designation,salary). Write a


function to add more records of employees in existing file [Link].
ii. Write a function Show() in Python that would read detail of employee from file
“[Link]” and display the details of those employee whose designation is “Salesman”.

import pickle
def add():
fo=open("[Link]","ab")
while True:
EID=int(input("Enter employee ID:"))
Ename=input("Enter name of an Employee:")
designation=input(“Enter Employee designation:”)
salary=int(input("Enter the salary:"))
rec=(EID,Ename,designation,salary)
[Link](rec,fo)
ch=input(“Do you want to enter more records?”)
if ch in ‘Nn’:
break
[Link]()
add()

def Show():
fo=open("[Link] ","rb")
found=0
print(“Details of those employees whose designation is Salesman are:”)
try:
while True:
rec=[Link](fo)
if rec[2]==”Salesman”:
found=1
print(rec)
except EOFError:
if found==0:
print(“No record found”)
[Link]()
Show()

10. A binary file [Link] has structure (rollno,name,class,percentage). Write a program


to updating a record in the file requires roll number to be fetched from the user whose
name is to be updated.
Import pickle
def update(rollno):
fo=open("[Link] ","rb+")
try:
while True:
rpos=[Link]()
record=[Link](fo)
rec=list(record)
if rec[0]==rollno:
name=input(“Enter name to update for the student:”)
rec[1]=name
r=tuple(rec)
[Link](rpos)
[Link](r,fo)

except EOFError:
[Link]()
rollno=int(input(“Enter rollno to update student name:”))
update(rollno)

11. Consider a binary file [Link] having records in the form of dictionary. E.g {eno:1,
name:”Rahul”, sal: 5000} write a python function to display the records of above file for
those employees who get salary between 25000 and 30000.

import pickle
def display():
fo=open("[Link] ","rb")
found=0
print(“Details of those employees whose designation is Salesman are:”)
try:
while True:
rec=[Link](fo)
if rec[2]==”Salesman”:
found=1
print(rec)
except EOFError:
if found==0:
print(“No record found”)
[Link]()
Show()

Common questions

Powered by AI

A function `CountRec(Author)` can be implemented to calculate the number of books by a specific author stored in a binary file 'Book.dat'. The function operates by opening the file in read (binary) mode and initializing a counter to zero. Using a loop, it reads each record from the file using `pickle.load()`, checks if the 'Author' field matches the input parameter, and increments the counter if it does. The function finally returns the counter value, which represents the number of books by the specified author .

The `add()` function enhances the file 'EMP.dat' by appending new employee records. It opens the file in append (binary) mode and repeatedly prompts the user to input values for employee ID, Name, and Salary. Each input set is packed into a list and serialized with `pickle.dump()`, appending the data to the file. The function includes a loop that allows the user to choose whether to add more records by entering a choice at the end of each iteration. The file is closed once the user opts not to add more records .

The function `countrec()` distinguishes and tallies students with percentages above 75 in 'STUDENT.DAT' by opening the file in read (binary) mode. It initializes a counter and iterates through each record using `pickle.load()`. During each iteration, it checks if the 'Percentage' field of the student record surpasses the threshold. If so, it increments the counter and prints the record details. The file is closed upon reaching EOF, after which it displays the total count of students meeting the criteria, providing an efficient way to tally based on a specific condition .

The `searchRollNo(r)` function locates a student's record in 'student.dat' by opening the file in read (binary) mode and using a loop to iterate through all records. It uses `pickle.load()` to deserialize each record and checks if the roll number in the record matches the parameter `r`. If a match is found, it sets a found flag to 1 and prints the student details. If the file reaches EOF without finding a match (indicating the flag remains 0), it outputs the message 'No record found', indicating the specific roll number was not located in the file .

The `frequency(name)` function determines how many times a customer has purchased an item by first opening the 'customerData.dat' file in read (binary) mode. It initializes a counter to zero and iterates through the records using `pickle.load()`. During each iteration, it checks if the 'customer name' field of the record matches the input parameter `name`. If a match is found, it increments the counter. The loop continues until an EOFError is raised, at which point the function closes the file and returns the counter value, representing the total purchases by the specified customer .

In Python, binary files are manipulated using the 'pickle' module to serialize and deserialize Python objects. For example, in managing a file 'Toy.dat' containing toy records with fields like Toy ID, Toy Name, Status, and MRP, a function `CreateFile()` is defined to input and store data records. The function opens the file in append (binary) mode, takes user input for each field, and uses `pickle.dump()` to serialize and write the record to the file. Similarly, `OnOffer()` function reads the file's contents to display only those records whose status is 'ON OFFER'. This is done by deserializing each record using `pickle.load()` and checking if the 'Status' field matches the specified criterion .

The `update(rollno)` function modifies a student's name in 'student.dat' by first opening the file in read (binary) and update mode ('rb+'). It uses a loop to iterate through the records, utilizing `pickle.load()` to deserialize each record and `fo.tell()` to get the current position in the file. When the record matching the specified 'rollno' is found, the name is updated based on user input, and the record is converted back to a tuple. The function then seeks back to the start position of the current record (`fo.seek(rpos)`) and overwrites it with the updated data using `pickle.dump()`. It finally closes the file after processing all records .

The function `Show()` identifies and displays records of employees designated as 'Salesman' by opening 'emp.dat' in read (binary) mode. It initializes a found flag to zero, then reads through the file using a loop with `pickle.load()`. For each record, it checks if the 'designation' field equals 'Salesman'. If a match is found, it sets the found flag to 1 and prints the record. If no matching records are found by the end of the file, it prints 'No record found' .

The function to append student records in 'student.dat' operates by opening the file in append (binary) mode using `pickle`. It ensures data integrity by collecting user input for each record field (Rollno, Name, Marks), organizing these inputs into a list, and then using `pickle.dump()` to append the serialized dictionary representation to the existing data in the file. By using append mode, the function preserves existing data in the file and maintains the correct order of records while adding new ones, thus ensuring that previous records are not overwritten or lost .

The `Display()` function filters products with a rating exceeding a threshold by opening 'product.dat' in read (binary) mode and iterating through its records. Each record is deserialized using `pickle.load()`, and its rating field is compared to the threshold value (10). If a record's rating exceeds the threshold, the function prints it and sets a flag to indicate that at least one matching record was found. If no matching records are found after traversing the entire file, it outputs 'No record found' .

You might also like