Writing String to Binary file
- To store string in binary file, we must convert it to binary
format either by prefixing the string with ‘b’ or using the
encode() function.
- For e.g.
We can use ‘a’ in
place of ‘w for
# Storing String in Binary Fi cl aa
msg="Welcome!"
£ = open('myfile. bin',
f£.write (msg-.encode ())
£.write(b' To Python Learning')
f£.close()
Welcome! To Python LearningReading Binary file in String
# Reading String from Binary File
f=open('myfile.bin','rb')
msg=f.read()
print (msg)
print (msg.decode())
f£.close()
b'Welcome! To Python Learning —=—
Welcome! To Python Learning
We can
observe,
italelnl
decoding it
aT lei
naeProgram to create Binary file and store few records in it
# Program to Create Binary File and storing Few Names
size of_rec = 20 #£ach name will occupy 20 bytes
with open(*Names.dat','wb') as £:
mo
while ans.lower (
name = input ("Enter Name :
1 = len (mame)
name = name + (size_of_rec-1)+'
# To add extra space with name to make it of length 20
name = name.encode ()
f£.write (name)
ans=input ("Add More 2")
}
Enee. Name SAMI?
aa tote “ey
Babor seme
Ada More ?y
pias ees
aa soso oe
Enter Namo :NOTIN
AaG More oy
scoeaue ei 2
Ada More ?7n
VIKAS
SsUMITAccessing record randomly from Binary File
# Brogram to Random Access any Name
+ First Name will be at position 0, second will be at 20 and so on
size_of rec = 20 ffach name will occupy 20 bytes
nun = int (input("Enser Record Number :"))
with open(*Names.dat', 'rb') as f:
f.seek(size of rect (mm-1)) #Sending read pointer to desired position
str = £.read(size_of rec)
Lf (Len (str) ==0) :
print ("Incorrect Position ")
else: Enter Name :AMIT
print (str.decode () ) Add More ?¥
Entex Name :VIRAS
Ada More 7y
Enter Name :SUMIT
Add More ?y
Enter Namo :NITIN
Ada More ?y
Enter Namo = SANcAY
Aaa Mors 7n
RECORD ORDER
Enter Record Number :
SUMIT
>>>
== RESTART: C:\Users\vin\Desk
Enter Record Number :10
Incorrect Position