Binary File Exam Based Questions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Binary File –Exam based questions

A binary file “student.dat” has structure [rollno, A binary file “emp.dat” has structure
name, marks]. [EID, Ename, designation, salary].
i. Write a user defined function insertRec() to i. Write a user defined function CreateEmp() to
input data for a student and add to input data for a record and create a file
student.dat. emp.dat.
ii. Write a function searchRollNo( r ) in Python ii. Write a function display() in Python to display
which accepts the student’s rollno as the detail of all employees whose salary is more
parameter and searches the record in the file than 50000.
“student.dat” (i)
and shows the details of student i.e. rollno, name import pickle
and marks (if found) otherwise shows the def CreateEmp():
message as ‘No record found’. f1=open("emp.dat",'wb')
eid=input("Enter E. Id")
(i) ename=input("Enter Name")
import pickle designation=input("Enter Designation")
def insertRec(): salary=int(input("Enter Salary"))
f=open("student.dat","ab") l=[eid,ename,designation,salary]
rollno = int (input("Enter Roll Number : ")) pickle.dump(l,f1)
name=input("Enter Name :") f1.close()
marks = int(input("Enter Marks : ")) (ii)
rec = [rollno, name, marks ] import pickle
pickle.dump( rec, f ) def display():
f.close() f2=open("emp.dat","rb")
(ii) try:
def searchRollNo( r ): while True:
f=open("student.dat","rb") rec=pickle.load(f2)
flag = False if rec[3]>5000:
while True: print(rec[0],rec[1],rec[2],rec[3])
try: except:
rec=pickle.load(f) f2.close()
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag == True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
Write a python program to append a new records Write a python program to search and display
in a binary file –“student.dat”. The record can the record of the student from a binary file
have Rollno, Name and Marks. “Student.dat” containing students records
import pickle (Rollno, Name and Marks). Roll number of the
while True: student to be searched will be entered by the
rollno = int(input("Enter your rollno: ")) user.
name = input("Enter your name: ")
marks = int(input("enter marks obtained: ")) import pickle
d = [rollno, name, marks] f1 = open("Student.dat", "rb")
f1 = open("Student.dat", "wb") rno = int(input(“Enter the roll no to search: ”))
pickle.dump(d, f1) flag = 0
choice = input("enter more records: y/n") try:
if choice== "N": while True:
break r = pickle.load(f1)
f1.close() if rno == r[0]:
print (rollno, name, marks)
flag = 1
except:
if flag == 0:
print(“Record not found…”)
f1.close()

i. A binary file “emp.DAT” has structure (EID, A binary file named “EMP.dat” has some records
Ename, designation,salary). Write a function to of the structure [EmpNo, EName, Post, Salary]
add more records of employes in existing file (a) Create a binary file “EMP.dat” that stores
emp.dat. the records of employees and display them one
ii. Write a function Show() in Python that would by one.
read detail of employee from file “emp.dat” and (b) Display the records of all those employees
display the details of those employee whose who are getting salaries between 25000 to
designation is “Salesman”. 30000.
(i) (a)
import pickle import pickle
def createemp: f1 = open('emp.dat','rb')
f1=open("emp.dat",'ab') try:
eid=input("Enter E. Id") while True:
ename=input("Enter Name") e = pickle.load(f1)
designation=input("Enter Designation") print(e)
salary=int(input("Enter Salary")) except:
l=[eid,ename,designation,salary] f1.close()
pickle.dump(l,f1)
f1.close() (b)
(ii) import pickle
def display(): f1 = open('emp.dat','rb')
f2=open("emp.dat","rb") try:
try: while True:
while True: e = pickle.load(f1)
rec=pickle.load(f2) if(e[3]>=25000 and e[3]<=30000):
if (rec[2]=='Manager'): print(e)
print(rec[0],rec[1], rec[2],rec[3]) except:
except: f1.close()
break
f2.close()

A binary file “Book.dat” has structure [BookNo,


Book_Name, Author, Price].
i. Write a user defined function CreateFile() to
input data for a record and add to “Book.dat”
.
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
“Book.dat”
(i)
import pickle
def createFile():
f=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author:" )
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,f)
f.close()
(ii)
def CountRec(Author):
f=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(f)
if Author==rec[2]:
num = num + 1
except:
f.close()
return num
A binary file student.dat has structure A binary file “STUDENT.DAT” has structure
(rollno,name,class,percentage). Write a program (admission_number, Name, Percentage). Write a
to updating a record in the file requires roll function countrec() in Python that would read
number to be fetched from the user whose contents of the file “STUDENT.DAT” and display
name is to be updated the details of those students whose percentage is
import pickle above 75. Also display number of students
import os scoring above 75%
f1 = open(‘student.dat','rb')
f2=open(“temp.dat”,”wb”) import pickle
r=int(input(“enter rollno which you want def CountRec():
to search”)) f=open("STUDENT.DAT","rb")
try: num = 0
while True: try:
e = pickle.load(f1) while True:
if e[0]==r: rec=pickle.load(f)
e[1]=input(“enter name”) if rec[2] > 75:
pickle.dump(e,f2) print(rec[0],rec[1],rec[2])
else: num = num + 1
pickle.dump(e,f2) except:
except: f.close()
f1.close() return num
f2.close()
os.remove(“student.dat”)
os.rename(“temp.dat”,”student,dat”)

A binary file named “EMP.dat” has some A binary file “Items.dat” has structure as [
records of the structure [EmpNo, EName, Post, Code, Description, Price ].
Salary] i. Write a user defined function MakeFile( ) to
(a) Write a user-defined function named input multiple items from the user and add
NewEmp() to input the details of a new employee to Items.dat
from the user and store it in EMP.dat. ii. Write a function SearchRec(Code) in Python
(b) Write a user-defined function named which will accept the code as parameter and
SumSalary(Post) that will accept an argument search and display the details of the
the post of employees & read the contents of corresponding code on screen from
EMP.dat and calculate the SUM of salary of all Items.dat. (i)
employees of that Post. import pickle
(a) def MakeFile( ):
import pickle while True:
def NewEmp ( ): code = input(“Enter Item Code :”)
f = open(“EMP.dat”,”wb”) desc = input(“Enter description
EmpNo = int(input(“Enter employee :”) price = float(input(“Enter
number: “)) price:”)) d= [code,desc,price]
EName = input(“Enter name:”) f = open (“Items.dat”, “ab”)
Post = input(“Enter post:”) pickle.dump( d,f )
Salary = int(input(“Enter salary”)) ch = input(“Add more record? (y/n)
rec = [EmpNo, Ename, Post,Salary] :”) if ch==’n’:
pickle.dump(rec, f) break
f.close() f.close( )
(b) (ii)
def SumSalary(Post): def SearchRec(code):
f = open("EMP.dat", "rb") f = open("Items.dat", "rb")
c=0 found = False
while True: while True:
try: try:
g = p.load(f) g = p.load(f)
if g[2]==Post: if g[0]==code:
c=c+g[3] print(g[0],g[1],g[2])
except: found=True
f.close() break
print("sum of salary", c) except:
if found == False:
print("No such record")
f.close()
A binary file named “TEST.dat” has some records Consider a binary file emp.dat having records in
of the structure [TestId, Subject, MaxMarks, the form of dictionary. E.g {eno:1, name:”Rahul”,
ScoredMarks] Write a function in Python named sal: 5000} write a python function to display the
DisplayAvgMarks(Sub) that will accept a subject records of above file for those employees who
as an argument and read the contents of get salary between 25000 and 30000
TEST.dat. The function will calculate & display the
Average of the ScoredMarks of the passed
Subject on screen.
def SumSalary(Sub): import pickle
f = open("ABC.dat", "rb") def search():
c=0 f=open(“emp.dat”,”rb”)
s=0 while True:
while True: try:
try: d=pickle.load(f)
g = p.load(f) if(d[‘sal’]>=25000 and
print(g) d[‘sal’]<=30000):
if g[1]==Sub: print(d)
s=s+g[3] except EOFError:
c=c+1 break
except: f.close()
f.close()
print("sum of salary", s/c)
f.close()
A binary file “Bank.dat” has structure as Consider an employee data, Empcode,
[account_no, cust_name, balance]. empname and salary.
i. Write a user-defined function addfile( ) and (i) Write python function to create
add a record to Bank.dat. binary file emp.dat and store
ii. Create a user-defined function CountRec( ) their records.
to count and return the number of customers (ii) write function to read and display
whose balance amount is more than 100000. all the records
(i) Ans
import pickle import pickle
def addfile( ): def add_record():
f = open(“bank.dat”,”wb”) f = open(“emp.dat”,”ab”)
acc_no = int(input(“Enter account empcode =int(input(“employee code:”))
number: “)) empname = int(input(“empName:”))
cust_name = input(“Enter name:”) salary = int(input(“salary:”))
bal = int(input(“Enter balance”)) d = [empcode, empname, salary]
rec = [acc_no, cust_name, bal] pickle.dump(d,f)
p.dump(rec, f) f.close()
f.close() import pickle
(ii)
def CountRec( ): def search():
f = open(“bank.dat”,”rb”) f=open(“emp.dat”,”rb”)
c=0 while True:
try: try:
while True: d=pickle.load(f)
rec = p.load(f) print(d)
if rec[2] > 100000: except EOFError:
c += 1 break
except: f.close()
f.close()
return c
Write a function SCOUNT( ) to read the content Given a binary file “emp.dat” has structure
of binary file “NAMES.DAT‟ and display number (Emp_id, Emp_name, Emp_Salary). Write a
of records (each name occupies 20 bytes in file function in Python countsal() in Python
) where name begins from “S‟ in it that
def SCOUNT( ): would read contents of the file “emp.dat” and
s=' ' display the details of those employee whose
count=0 salary is greater than 20000
f=open('Names.dat', 'rb'): import pickle
while True: def countsal():
s = f.read(20) f = open (“emp.dat”, “rb”)
if len(s)!=0: n=0
if s[0].lower()=='s': try:
count+=1 while True:
print('names beginning from "S" are ',count) rec = pickle.load(f)
if rec[2] > 20000:
print(rec[0], rec[1], rec[2])
n=n+1
except:
print(n)
f.close()
Write Python function DISPEMP( ) to read the Consider the following CSV file (emp.csv):
content of file emp.csv and display only those Sl,name,salary
records where salary is 4000 or above 1,Peter,3500
import csv 2,Scott,4000
def DISPEMP(): 3,Harry,5000
csvfile=open('emp.csv'): 4,Michael,2500
myreader = csv.reader(csvfile,delimiter=',') 5,Sam,4200
print(EMPNO,EMP NAME,SALARY) Write Python function DISPEMP( ) to read the
for row in myreader: content of file emp.csv and display only those
if int(row[2])>4000: records where salary is 4000 or above
print(row[0], row[1],row[2]) import csv
def DISPEMP():
csvfile=open('emp.csv'):
myreader = csv.reader(csvfile,delimiter=',')
print(EMPNO,EMP NAME,SALARY)
for row in myreader:
if int(row[2])>4000:
print(row[0], row[1],row[2])

A binary file “Stu.dat” has structure (rollno, A binary file “Stu.dat” has structure (rollno,
name, marks). name, marks).
Write a function in Python add_record() to input
data for a record and add to Stu.dat.
import pickle Write a function in python Search_record() to
def add_record(): search a record from binary file “Stu.dat” on the
fobj = open(“Stu.dat”,”ab”) basis of roll number.
rollno =int(input(“Roll no:”)) def Search_record():
name = int(input(“Name:”)) f = open(“Stu.dat”, “rb”)
marks = int(input(“Marks:”)) stu_rec = pickle.load(f)
data = [rollno, name, marks] found = 0
pickle.dump(data,fobj) rno = int(input(“roll number to search:”))
fobj.close() try:
for R in stu_rec:
if R[0] == rno:
print (R[1], “Found!”)
found = 1
break
except:
if found == 0:
print (“Sorry, record not found:”)
f.close()

Amritya Seth is a programmer, who has recently been given a task to write a
python code to perform the following binary file operations with the help of
two user defined functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing student information – roll
number, name and marks (out of 100) of each student.
b. GetStudents() to display the name and percentage of those students who have a percentage greater
than 75. In case there is no student having percentage > 75 the function displays an appropriate
message. The function should also display the average percent.

He has succeeded in writing partial code and has missed out certain statements, so he has left certain
queries in comment lines. You as an expert of Python have to provide the missing statements and
other related queries based on the following code of Amritya. Answer any four questions (out of five)
from the below mentioned questions.

import pickle
def AddStudents():
____________ #1 statement to open the binary file to
write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
____________ #2 statement to write the list L
into the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()

def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
____________ #3 statement to read
from the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =
",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has
percentage more than 75")
average=Total/Countrec
print("average percent of class = ",average)
AddStudents()
GetStudents()

Which of the following commands is used to open the file “STUDENT.DAT”


for writing only in binary format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')
Correct Answer : a. F= open("STUDENT.DAT",'wb')

Which of the following commands is used to write the list L into the binary file,
STUDENT.DAT? (marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
Correct Answer : c. pickle.dump(L,F)
Which of the following commands is used to read each record from the binary
file STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
Correct Answer : a. R = pickle.load(F)
Which of the following statement(s) are correct regarding the file access
modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its
beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the
existing file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites
the file if it exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file
if the file exists.
Correct Answer : a

Which of the following statements correctly explain the function of seek()


method?
a. tells the current position within the file.
b. determines if you can move the file position or not.
c. indicates that the next read or write occurs from that position in a file.
d. moves the current file position to a given specified position
Correct Answer: d
(i) Differentiate between r+ and w+ file modes in Python. (QUES no. 34 or 35 in BOARD EXAM)

(ii) Consider a file, SPORT.DAT, containing records of the following


structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with
Sport name as “Basket Ball”o the file named BASKET.DAT. The function should return the total number
of records copied to the file BASKET.DAT.
OR
(i) How are text files different from binary files?

(ii) A Binary file, CINEMA.DAT has the following structure:


{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the
records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype

You might also like