Python program to modify the content of a Binary File
Last Updated :
27 Dec, 2021
Given a binary file that contains some sentences (space separated words), let’s write a Python program to modify or alter any particular word of the sentence.
Approach:
Step 1: Searching for the word in the binary file.
Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading of the record.
Step 3: If the word to be searched exists then place the write pointer (to ending of the previous record) i.e. at pos.
Step 4: Call write() function to take the new record.
Step 5: Write the new object at the position “pos” and hence the record is updated and print “record successfully updated”.
Step 6: If the word does not exists then print “record not found”.
Implementation
Let’s suppose the content of the binary file is:
Python3
def update_binary(word, new)
string = b""
Flag = 0
with open ( 'file.txt' , 'r + b' ) as file :
pos = 0
data = string = file .read( 1 )
while data:
data = file .read( 1 )
if data = = b " " :
if string = = word:
file .seek(pos)
file .write(new)
Flag = 1
break
else :
pos = file .tell()
data = string = file .read( 1 )
else :
string + = data
continue
if Flag:
print ( "Record successfully updated" )
else :
print ( "Record not found" )
word = input ( "Enter the word to be replaced: " ).encode()
new = input ( "\nEnter the new word: " ).encode()
update_binary(word, new)
|
Output:
Text file:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...