File Handling
File Handling
File Handling
File opening mode must attach „b‟ to it for operating binary file(Ex: „rb‟- for reading)
Pickle module: pickle module is used in binary file for load( ) and dump( ) methods which
are used for reading and writing into binary file respectively.
pickle Module: - Before reading or writing to a file, we have to import the pickle module.
import pickle
pickle.dump() – This method is used to write the object in the file which is opened in „wb‟ or
„ab‟ i.e. write binary or append binary access mode respectively.
Syntax : pickle.dump(<structure>,<FileObject>)
import pickle
fo = open("binary_file1.dat","wb")
Laptop = ["Dell","HP","ACER"]
pickle.dump(Laptop,fo)
fo.close()
pickle.load() – This method is used to read data from a file and return back into the structure
(list/dictionary).
import pickle
fbin = open("binary_file1.dat","rb")
x=pickle.load(fbin)
print(x)
fbin.close()
import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()
f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()
(a) Write a user defined function CreateFile() to input data for a record and add
to Book.dat.
import pickle
def createFile():
record=[]
while True:
File=open("BOOK.DAT","ab")
data=[BookNo,Book_Name,Author,Price]
record.append(data)
if ch=='n':
break
pickle.dump(record,File)
File.close()
def CountRec(Author):
File=open("BOOK.DAT","rb")
rec=pickle.load(File)
count=0
for r in rec:
if r[2]==Author:
count=count+1
File.close()
return count
#main
##createFile()
import pickle
def addBook():
record=[]
while True:
File=open("LIB.DAT","ab")
BookNo=int(input("Enter Book Code : "))
data=[BookNo,Book_Name,Author,Price]
record.append(data)
ch=input("continue ..")
if ch=='n':
break
pickle.dump(record,File)
File.close()
(b) Write a user defined function in Python which accepts a book no. from
a userto search and print the details of it. If no such book exists, then
print a relevant message for the user.
def search_book():
File=open("LIB.DAT","rb")
rec=pickle.load(File)
found=0
for r in rec:
if r[0]==Bno:
print(r[0],r[1],r[2],r[3],sep='\t')
found=1
break
if found==0:
File.close()
Q4. For a file "LIB.DAT” containing details of all the books, write a function
in Pythonto increase the price by 50/- of each book of "ABP” publisher by
using tell andseek function.
import pickle
def modify_data():
file=open('LIB.DAT','rb+')
found=0
try:
loc=file.tell()
record=pickle.load(file)
for r in record:
if r[1]=='IP':
r[3]=r[3]+50
file.seek(loc)
pickle.dump(record,file)
print("Modified Record")
found=1
break
if found==0:
file.close()
exceptEOFError:
Q5. For a binary file TELE.DAT, containing the records of the following List:
Mob_list=[aust_id,cust_name, mobile_no]
Note: mobile no is of type string
Write a function in Python that would read details from a file
"TELE.DAT"andmodify the mobile number by 7 which are starting with
digit 8.
Q6. For a binary file LIB.DAT, containing the records of the following List:
Library=[b_no, b_name, b_title, b_price]
Write a user defined function to remove a record from a file "LIB.DAT"
by using b_no.
import pickle
def bf_delete():
f = open("LIB.DAT","rb")
data=pickle.load(f)
f.close()
f = open("LIB.DAT","wb")
lst=[]
if record[0]==b_no:
continue
lst.append(record)
pickle.dump(lst,f)
f.close()
defcopy_book():
file1=open("TextBook.dat",'rb')
file2=open("NoteBook.dat",'wb')
record1=[]
record=pickle.load(file1)
for i in record:
if i[1]%2==0:
record1.append(i)
pickle.dump(record1,file2)
file1.close()
file2.close()
Cust={„cust_no‟:______________, „cust_name‟:______________}
File=open(“customer.dat”, “rb”)
try:
while True:
record=pickle.load(file)
if record[cust_no]=s_rec:
print(record[cust_no],record[cust_name], sep=‟\t‟)
except EOFError:
file.close()
Q9. Consider the following definition of dictionary cust and define a function
inPython to read a file "customer.dat” and print record of customers from a
binary file "customer.dat" whose salary is less than 20000/-. Assume that file
contains record of 100 customers.
Custs={„cust_no‟:______________, „cust_name‟:______________,
„salary‟:_________}
def search_data():
file=open(“customer.dat”, „rb‟)
try:
while True:
record=pickle.load(file)
if record[salary]<20000:
c_no=record[cust_no]
c_nm=record[cust_name]
c_sal=record[Salary]
print(c_no,c_nm,c_sal, „\t‟)
except EOFErorr:
file.close()
Write a function to generate an electricity bill as per the following criteria and
store it in a binary file "electricity.dat”
Unit usage Ami_per_unit
0-50 free
51-100 80 paisa
101-200 1.20 paisa
Above 200 1.50 paisa
Import pickle
def write_data():
Electricity=[]
file=open('Electricity.dat','ab')
if unit_usage<=50:
tot_amt=0
elif unit_usage<=100:
amt_per_unit=0.80
elif unit_usage<=200:
amt_per_unit=1.20
else:
amt_per_unit=1.50
tot_amt=unit_usage*amt_per_unit
pickle.dump(Electricity,file)
file.close()
Write a function to read a file electricity.dat and print the bill on screen of all
customers whose bill amount is more than ₹ 1000 present in a file.
def read_data():
file=open('Electricity.dat','rb')
try:
while True:
record=pickle.load(file)
if record[4]>1000:
print(record)
except EOFError:
pass
file.close()
Q12. (a) A binary file "Bank.dat" has structure AccNo, AccHolder, Acc Type,
Bal. Write a user defined function add_rec() to accept all details of customer
and append the data into a file "Bank.dat".
import pickle
def add_rec():
file=open("Bank.dat", 'ab')
bankRec=[]
while True:
bankRec.append(data)
if ch=='N': break
pickle.dump(bankRec,file)
file.close()
file=open("Bank.dat", 'rb')
try:
count=0
while True:
record=pickle.load(file)
if record[2] is 'Ss':
count=count+1
exceptEOFError:
pass
file.close()
return count
import pickle as p
def write_data():
file=open('stud.dat', 'wb')
record=[]
Per=(M_Physics+M_Chemistry+M_Maths)/3
record.append(data)
p.dump(record,file)
file.close()
import pickle as p
def read_data():
file=open('stud.dat', 'wb')
try:
while True:
data=p.load(file)
per=(data[2]+data[3]+data[4])/3
r=data[0]
nm=data[1]
m1=data[2]
m2=data[3]
m3=data[4]
print(r,nm,m1,m2,m3,per, sep='\t')
except EOFError:
pass
file.close()
import pickle as p
def display_result():
file= open('Studet.dat','rb')
while True:
try:
Stud=p.load(file)
Roll_no=Stud[0]
Name=Stud[1]
Marks1=Stud1[2]
Marks2=Stud1[3]
Marks3=Stud1[4]
avg=(Marks1+Marks2+Marks3)/3
except Exception:
pass
file.close()
Q17. Given a binary file PHONE DAT, containing records of the following
dictionary:
Phonlist={'name':name,'address':address,'phone':phone}
Write a function TRANSFER() in Python that would copy all those records
which are having Phone no starts with 8 from PHONE.DAT to
PHONBACK.DAT
def search():
file1=open('PHONBACK.DAT', 'wb')
while True:
try:
record = pickle.load(file)
if int(record['phone'])//1000000000==9:
print(record['phone'])
rec=record
print(rec)
pickle.dump(record,file1)
except EOFError:
break
file.close()
file1.close()
Q18. Consider a list Vehicle containing vehicle name of type string, sitting
capacity of type integer
import pickle
def create_data():
fr=open('CARS.DAT','rb')
fw=open('TAXI.DAT','wb')
count=0
while True:
try:
record=pickle.load(fr)
pickle.dump(record,fw)
count + =1
except Exception:
break
fr.close()
fw.close()
return count
#main program
create_data()
Q19. Write a function search_candiate() in Python to search a record by
candidate id from a binary file. “candidate.dat”. If the record is not found
then print the appropriate message. File contains the record of the following
list:
import pickle as p
def search_candidate():
file=open("candidate.dat,"rb")
try:
while True:
rec=p.load(file)
if rec[0]=cid:
print(rec[0],rec[1],rec[2],sep='\t')
break
except EOFError:
file.close()
def search():
file = open("Telephone.dat","rb")
file1=open('Backup.dat', 'wb')
while True:
try:
record = pickle.load(file)
if int(record['phone'])==11:
pickle.dump(record,file1)
except EOFError:
print(“File copied”)
file.close()
file1.close()
def b=new_connections():
file=open("NConn.dat",'ab')
rec=[]
name=input("Enter name")
if ar_c==11:
rec={"PhoneNo": pno,"C_Name":name,"Areacode":ar_c}
pickle.load(rec,file)
file.close()
Program
import pickle
def set_data():
print()
#create a dictionary
student = {}
student['rollno'] = rollno
student['name'] = name
student['test_score'] = test_score
return student
def display_data(student):
print()
def write_record():
pickle.dump(set_data(), outfile)
outfile.close()
def read_records():
while True:
try:
student = pickle.load(infile)
except EOFError:
break
infile.close()
def search_record():
flag = False
while True:
try:
student = pickle.load(infile)
if student['rollno'] == rollno:
display_data(student)
flag = True
break
except EOFError:
break
if flag == False:
print()
infile.close()
def show_choices():
print('Menu')
print('4. Exit')
def main():
while(True):
show_choices()
print()
if choice == '1':
write_record()
elif choice == '2':
read_records()
search_record()
break
else:
print('Invalid input')
main()
Output
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 2
Roll number: 21
Name: Jyotsna
Test Score: 78
Roll number: 22
Name: Satyam
Test Score: 99
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 3
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 3
Roll number: 22
Name: Satyam
Test Score: 99
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4
Q 2. Write a menu driven program in Python that asks the user to add, display, and
search records of employee stored in a binary file. The employee record contains
employee code, name and salary. It should be stored in a list object. Your program
should pickle the object and save it to a binary file.
Program
import pickle
def set_data():
empcode = int(input('Enter Employee code: '))
name = input('Enter Employee name: ')
salary = int(input('Enter salary: '))
print()
#create a list
employee = [empcode,name,salary]
return employee
def display_data(employee):
print('Employee code:', employee[0])
print('Employee name:', employee[1])
print('Salary:', employee[2])
print()
def write_record():
#open file in binary mode for writing.
outfile = open('emp.dat', 'ab')
def read_records():
#open file in binary mode for reading
infile = open('emp.dat', 'rb')
except EOFError:
break
if flag == False:
print('Record not Found')
print()
def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')
def main():
while(True):
show_choices()
choice = input('Enter choice(1-4): ')
print()
if choice == '1':
write_record()
else:
print('Invalid input')
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 2
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 3
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4