📜  修改二进制文件内容的Python程序

📅  最后修改于: 2022-05-13 01:54:58.672000             🧑  作者: Mango

修改二进制文件内容的Python程序

给定一个包含一些句子(空格分隔的单词)的二进制文件,让我们编写一个Python程序来修改或更改句子的任何特定单词。

方法:
第 1 步:在二进制文件中搜索单词。
第二步:在文件中搜索时,变量“pos”存储文件指针记录的位置,然后遍历(继续)读取记录。
第 3 步:如果要搜索的单词存在,则将写指针(指向上一条记录的结尾)放置在 pos 处。
第 4 步:调用 write()函数获取新记录。
步骤 5:在“pos”位置写入新对象,从而更新记录并打印“记录成功更新”。
步骤 6:如果单词不存在,则打印“record not found”。

执行
假设二进制文件的内容是:

python-二进制文件输入

Python3
# Python program to modify the
# content of binary file
 
 
# Function to update the
# content of binary file
def update_binary(word, new)
    # string variable to store
    # each word after reading
    # from the file
    string = b""
 
    # Flag variable to check
    # if the record is found or
    # not
    Flag = 0
 
    # Open the file in r + b mode which means
    # opening a binary file for reading and
    # writing
    with open('file.txt', 'r + b') as file:
 
        pos = 0
 
        # Reading the content of the
        # file character by character
        data = string = file.read(1)
 
        # Looping till the end of
        # file is reached
        while data:
            data = file.read(1)
 
            # Checking if the space is reached
            if data == b" ":
 
                # checking the word read with
                # the word entered by user
                if string == word:
 
                    # Moving the file pointer
                    # at the end of the previously
                    # read record
                    file.seek(pos)
 
                    # Updating the content of the file
                    file.write(new)
                    Flag = 1
                    break
                else:
                    # storing the position of
                    # current file pointer i.e. at
                    # the end of previously read record
                    pos = file.tell()
                    data = string = file.read(1)
            else:
 
                # Storing the data of the file
                # in the string variable
                string += data
                continue
 
 
    if Flag:
        print("Record successfully updated")
    else:
        print("Record not found")
         
         
# Driver code
# Input the word to be found
# and the new word
word = input("Enter the word to be replaced: ").encode()
new = input("\nEnter the new word: ").encode()
 
update_binary(word, new)


输出:

python-二进制文件-输出-1

文本文件:

python-二进制文件-输出-2