You are on page 1of 15

Binary File – Contd..

Using with statement


• The with statement is a compact statement which
combines the opening of file and processing of file
along with inbuilt exception handling.
• Syntax is,
with open (filename,filemode) as filehandle:
file manipulation statements
• Example:
with open (“notes.txt”,’w’) as f:
f.write(“This is my file”)
Advantages of with statement
• The with statement will automatically close
the file after the block of code.
• Even if an exception (runtime error) occurs
before the end of the block, the with
statement will handle it and close the file.
• You need not mention any exception with the
with statement explicitly.
Reading from a file - using with
statement
import pickle
st = {}
with open("stud.dat","rb") as f1:
print("File stud.dat contains...")
stu=pickle.load(f1)
print(stu)

Output:
File stud.dat contains...
{'rn': 123, 'name': 'Ajay', 'marks': 56.0}
Writing to a file – using with statement
import pickle
st={}
with open("stud.dat","wb") as f1:
ans="y"
while ans=="y":
rn = int(input("Enter Roll No:"))
name = input("Enter Name:")
marks = float(input("Enter Marks:"))
st['rn'] = rn
st['name'] = name
st['marks']=marks
pickle.dump(st,f1)
ans=input("Do you want to enter more records?(y/n)")
Output
Enter Roll No:1001
Enter Name:"Geetha"
Enter Marks:45
Do you want to enter more records?(y/n)"n”

File stud.dat contains...


{'rn': 1001, 'name': 'Geetha', 'marks': 45.0}
Using with & dump – another example
import pickle
stmt = "This is my first line. This is second line."
with open("myfile.info","wb") as f:
pickle.dump(stmt,f)
print("Successfully Created")

Output
Successfully Created
Using with & load – another example
import pickle
stmt = " "
with open("myfile.info","rb") as f:
stmt = pickle.load(f)
print(stmt)
Output
This is my first line. This is second line.
Display all text before letter ‘o’
import pickle
stmt = " "
with open("myfile.info","rb") as f:
stmt = pickle.load(f)
lst=stmt.split('o')
print(lst[0])
Output
This is my first line. This is sec
Searching in a file
• There are multiple ways of searching for a
value stored in a file.
• The simplest search technique is sequential
search whereby we read records from the file
one by one and then look for the search key in
the read record.
Searching Procedure
1. Open the file in read mode.
2. Read the file contents record by record (i.e. object
by object).
3. In every read record, look for the desired search-
key.
4. If found, process as desired.
5. If not found, read the next record and look for the
desired search-key.
6. If search-key is not found in any of the records,
report that no such value found in the file.
Search for records
import pickle
st={}
found = False
searchkeys = list(input("Enter the roll nos to be searched for"))
f1=open("stud.dat","rb")
try:
print("Searching in file stud.dat...")
while True:
st=pickle.load(f1)
if st['rn'] in searchkeys:
print(st)
found = True
except EOFError:
if found == False:
print("No such record found in the file")
else:
print("Search successful")
f1.close()
Output
Enter the roll nos to be searched for[15,19]
Searching in file stud.dat...
No such record found in the file

----------------------------------------------------------------------------------

Enter the roll nos to be searched for[999,123]


Searching in file stud.dat...
{'rn': 999, 'name': 'Raj', 'marks': 65.0}
{'rn': 123, 'name': 'Sab', 'marks': 56.0}
Search successful
Display records based on cut off marks
import pickle
st={}
found = False
m = int(input("Enter the cut off marks"))
print("Searching in file stud.dat...")
f1=open("stud.dat","rb")
try:
while True:
st=pickle.load(f1)
if st['marks']>m:
print(st)
found = True
except EOFError:
if found == False:
print("No such record found in the file")
else:
print("Search successful")
f1.close()
Output
Enter the cut off marks30
Searching in file stud.dat...
{'rn': 999, 'name': 'Raj', 'marks': 65.0}
{'rn': 123, 'name': 'Sab', 'marks': 56.0}
{'rn': 14, 'name': 'Resh', 'marks': 96.0}
Search successful
----------------------------------------------------------------------------------------
Enter the cut off marks65
Searching in file stud.dat...
{'rn': 14, 'name': 'Resh', 'marks': 96.0}
Search successful
--------------------------------------------------------------------------------------------
Enter the cut off marks98
Searching in file stud.dat...
No such record found in the file

You might also like