0% found this document useful (0 votes)
388 views8 pages

Python Binary File Operations Guide

The document provides Python code solutions to various problems involving binary files. These include: 1. Functions to create, read from, and count records in binary files based on certain criteria like author name or percentage. 2. Functions to search, add, modify and delete records in binary files. 3. Code to update a record in a binary file based on an ID entered by the user and write the updated record to a new file. The problems cover concepts like opening binary files in read/write/append modes, using pickle module to dump and load objects, iterating through file contents, and performing various operations on records based on conditions.

Uploaded by

V.R. Murugan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
388 views8 pages

Python Binary File Operations Guide

The document provides Python code solutions to various problems involving binary files. These include: 1. Functions to create, read from, and count records in binary files based on certain criteria like author name or percentage. 2. Functions to search, add, modify and delete records in binary files. 3. Code to update a record in a binary file based on an ID entered by the user and write the updated record to a new file. The problems cover concepts like opening binary files in read/write/append modes, using pickle module to dump and load objects, iterating through file contents, and performing various operations on records based on conditions.

Uploaded by

V.R. Murugan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Binary File Operations: Q1
  • Binary File Operations: Q2 & Q3
  • Binary File Operations: Q4 & Q5
  • Binary File Operations: Q6 & Q7
  • Binary File Operations: Q8 & Q9
  • Binary File Operations: Q10
  • Binary File Operations: Q11 - Q12
  • Binary File Operations: Q13

BINARY FILE OPERATIONS:

Q1. A binary file “[Link]” has structure [BookNo, Book_Name, Author,


Price].

1. Write a user defined function CreateFile() to input data for a record and add
to [Link] .
2. 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():
fobj=open("[Link]","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
[Link](rec, fobj)
[Link]()

createfile() # This fn is called just to verify result and not required in exam

def countrec(Author):
fobj=open("[Link]", "rb")
num = 0
try:
while True:
rec=[Link](fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except:
[Link]()
return num

n=countrec("amit") # This fn is called just to verify result and not required in exam
print("Total records", n) # This stt is just to verify result and not required in exam
Q2. 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():
fobj=open("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
[Link]()
return num

Q3 Write a function in python to search and display details, whose destination is


“Cochin” from binary file “[Link]”. Assuming the binary file is containing the
following elements in the list:
1. Bus Number [Link] Starting Point [Link] Destination
import pickle
def countrec():
fobj=open("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
[Link]()
return num
n=countrec() # This function is called just to verify result
print(n)
Q4. Write a function addrec() in Python to add more new records at the bottom of a
binary file “[Link]”, assuming the binary file is containing the following
structure :
[Roll Number, Student Name]

import pickle
def addrec():
fobj=open("[Link]","ab")
rollno=int(input("Roll Number : "))
sname=input("Student Name :")
rec=[rollno,sname]
[Link](rec,fobj)
[Link]()
addrec()

Q5. Write a function searchprod( pc) in python to display the record of a particular
product from a file [Link] whose code is passed as an argument. Structure of
product contains the following elements
[product code , product price]

import pickle
def searchprod(pc):
fobj=open("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[0]==pc:
print(rec)
except:
[Link]()

n=searchprod(1) # This function is called to verify the result


Q6. Write a function routechange(route number) which takes the Route number as
parameter and modify the route name(Accept it from the user) of passed route
number in a binary file “[Link]”.

import pickle
def routechange(rno):
fobj=open("[Link]","rb")
try:
while True:
rec=[Link](fobj)
if rec[0]==rno:
rn=input("Enter route name to be changed ")
rec[1]=rn
print(rec) #This stt is called to verify the change in the record
except:
[Link]()

routechange(1) # This function is called to verify the result

Q7. Write a function countrec(sport name) in Python which accepts the name of
sport as parameter and count and display the coach name of a sport which is passed
as argument from the binary file “[Link]”. Structure of record in a file is given
below ——————– – [sport name, coach name]

def countrec(sn):
num=0
fobj=open("[Link]","rb")
try:
print("Sport Name","\t","Coach Name")
while True:
rec=[Link](fobj)
if rec[0]==sn:

print(rec[0],"\t\t",rec[1])
num=num+1
return num
except:
[Link]()
Q8. A binary file “[Link]” has structure [employee id, employee name,
salary]. Write a function countrec() in Python that would read contents of the file
“[Link]” and display the details of those employee whose salary is above
20000.
def countrec():
num=0
fobj=open("[Link]","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=[Link](fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
[Link]()

countrec()# This function is called to verify the result

Q9. Amit is a monitor of class XII-A and he stored the record of all the students of
his class in a file named “[Link]”. Structure of record is [roll number, name,
percentage]. His computer teacher has assigned the following duty to [Link] a
function remcount( ) to count the number of students who need remedial class
(student who scored less than 40 percent)

def countrec():
fobj=open("[Link]","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=[Link](fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
[Link]()

countrec()# This function is called to verify the result


Q10. A binary file “[Link]” has structure [employee id, employee name].
Write a function delrec(employee number) in Python that would read
contents of the file “[Link]” and delete the details of those employee whose
employee number is passed as argument.
import pickle
import os
def delrec:
num=0
f=open(“[Link]”,”rb”)
ftemp=open(“[Link]”,”wb”)
eid=int(input(“enter emp id”))
try:
while True:
rec=[Link](f)
if rec[0] == eid:
print(“Rec found”)
else:
[Link](rec,ftemp)
except:
[Link]()
delrec() # fn call
[Link](“[Link]”)
[Link](“[Link]”,”[Link]”)

def display():
f= open(“[Link]”,”rb”)
try:
while True:
rec=[Link](f)
print(rec)
except [Link]()
display() # fn call

11) Tarun is a Python programmer. He has written a code and created a binary file
“[Link]” with Teach_Id, Tname and Tsalary. The file contains 10 records. He now
has to update a record based on the employee Tid entered by the user and update the
salary. The updated record is then to be written in the file [Link]. The records which
are not to be updated also have to be written to the file [Link]. If the Teacher id is not
found, an appropriate message should to be displayed. As a Python expert, help him to
complete the following code based on the requirement given above:

import _______ # Line1 pickle


def update_rec():
rec={}
inf=open("[Link]","rb")
outf=open("_____________") #Line 2 ( “[Link]”,’wb’)
found=False
Tid=int(input("Enter Teacher id to update their salary))
while True:
try:
rec= [Link](inf)
if ________________________ #Line 3 if rec[“Teach_Id”== Tid]

found=True
rec["Tsalary"]=int(input("Enter new salary :: "))
pickle.____________ #Line 4 [Link](rec,outf)

else:
[Link](rec,outf)
except:
break
if found==True:
print("The salary of Teacher id ",Teach_Id," has been updated.")
else:
print("No employee with such id is not found")
[Link]()
[Link]()
(i) Which module should be imported in the program? (Line 1)
(ii) Write the correct statement required to open a temporary file named
[Link].? (Line 2)
(iii) Which statement should Tarun fill in Line 3 to readand check the
Teach_Id with given Tid from the binary file [Link]
and in Line 4 to write the updated data in the file [Link]?
12) 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():
fobj=open("[Link]","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input(“Author: “)
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
[Link](rec,fobj)
[Link]()
def CountRec(Author):
fobj=open("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if Author==rec[2]:
num = num + 1
except:
[Link]()
return num

13) 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():
fobj=open("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[2] > 75:
print(rec[0],rec[1],rec[2],sep="\t")
num = num + 1
except:
[Link]()
return num

Common questions

Powered by AI

Error handling in binary file operations is crucial for maintaining application stability and data integrity. The provided source code functions typically wrap file access and iteration in try-except blocks to catch EOFError, signaling the end of file processing, which prevents program crashes from attempted reading beyond the file's end. However, these functions could benefit from more comprehensive error handling, such as dealing with IOError for file access issues and ensuring data type validations. Effective error handling manages unexpected conditions gracefully, ensuring reliable function execution and safeguarding against data corruption .

The 'routechange' function modifies route information by taking a route number as its argument, searching through 'route.dat' for a matching record, and allowing the user to update the route name. During execution, it iterates through the file, updating only the relevant record while leaving others unchanged. The updated records must be carefully managed to ensure data integrity, as incorrect handling during modification could lead to data inconsistencies or loss. The implication is strong with respect to maintaining accurate and current records in a dynamically accessed system .

The 'delrec' function implements an efficient data deletion process in a binary file by reading each record and comparing it against the specified employee number for deletion. It employs a temporary file ('temp.dat') to write all records except the one marked for deletion, ensuring no data is lost mistakenly. This two-step process (copying and renaming) simplifies error recovery and preserves data integrity, as the deletion is only finalized once verification is complete. This approach minimizes the risk of accidental deletions and maintains the file's structural integrity .

Using the 'pickle' module for data serialization offers significant benefits, including simplicity in saving complex data structures and Python object preservation. It is inherently Pythonic and ensures seamless storage and retrieval of objects without extensive format management. However, potential drawbacks include security risks from untrusted sources as pickle files can include executable code. Moreover, compatibility issues arise across different Python versions, and the module does not support infinite data types, posing limitations for diverse applications. The trade-offs highlight a need for cautious use, especially in environments requiring robust security standards .

The 'createfile' function facilitates data management by allowing the user to input records with attributes such as BookNo, Book_Name, Author, and Price into the binary file 'Book.dat'. This function opens the file in append binary mode, ensuring that new records can be added without overwriting existing data. It employs the 'pickle.dump' method to serialize and save the data structure (list) into the file. This is crucial for maintaining a persistent and retrievable state of book records, which enhances data organization and accessibility within a specific data structure .

The 'addrec' function facilitates seamless addition of new student records to 'STUDENT.dat' by opening the file in append binary mode ('ab'). This mode ensures that new records are added to the end of the file without disturbing existing data. Upon user input (Roll Number and Student Name), records are serialized and written using the 'pickle.dump' method. This design prevents overwriting, maintains the file's cumulative integrity, and facilitates easy data retrieval for subsequent operations, ensuring a robust and expandable data storage solution .

The 'update_rec()' function facilitates updating teacher records by prompting the user to input the teacher ID and new salary, updating the record if the ID matches, and writing it back to a temporary file, ensuring non-matching records are retained. Key components missing in its implementation include the proper import statement for the 'pickle' module, specific read operations to confirm matching IDs, and the complete setup for opening and writing to the temporary 'Temp.dat' file. Filling in these missing code elements is crucial for ensuring proper functionality and database updates, preventing data impairment, and ensuring operational integrity .

The 'searchprod' function efficiently retrieves specific product records by iterating over 'product.dat' and checking each record's product code against the provided argument. The use of the 'pickle.load' method allows for seamless deserialization of records, while a simple condition ensures only the desired product details are displayed. While effective for small to moderate-sized files, its linear search strategy may be less efficient for larger files, where an indexed or hashed approach could potentially enhance speed and efficiency .

The 'countrec' function effectively extracts student records from 'STUDENT.DAT' where the percentage is above 75 by iterating through the file and checking each record's percentage field. The use of a simple conditional statement ensures only relevant records are printed and counted. This method is efficient, yielding accurate results for potential reviewers or stakeholders interested in academic performance. However, the reliance on iteration can be computationally intense if the file size is large, and the approach doesn't provide error handling for corrupt files or non-numeric percentages, which could be improved upon .

The 'CountRec' function plays a vital role in analyzing author-specific data by counting and returning the number of books authored by a specified individual in 'Book.dat'. It does this by iterating over each record in the binary file, checking if the 'Author' field matches the input parameter, and incrementing the count accordingly. This function allows for efficient retrieval and analysis of data concerning a specific author's contributions, which is crucial for data categorization and reporting .

BINARY FILE OPERATIONS:
Q1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, 
    Price].
1. Write a user d
Q2. A binary file “STUDENT.DAT” has structure [admission_number, Name, 
Percentage]. Write a function countrec() in Python th
Q4. Write a function addrec() in Python to add more new records at the bottom of a
binary file “STUDENT.dat”, assuming the bi
Q6. Write a function routechange(route number) which takes the Route number as 
parameter and modify the route name(Accept it
Q8. A binary file “salary.DAT” has structure [employee id, employee name, 
salary]. Write a function countrec() in Python tha
Q10. A binary file “emp.dat” has structure [employee id, employee name]. 
Write a function delrec(employee number) in Python
found, an appropriate message should to be displayed. As a Python expert, help him to
complete the following code based on th
fobj=open("Book.dat","ab") 
BookNo=int(input("Book Number : ")) 
Book_name=input("Name :") 
Author = input(“Author: “) 
Price

You might also like