Professional Documents
Culture Documents
Binary File 2
Binary File 2
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”
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
----------------------------------------------------------------------------------