Trimax
Trimax

Reputation: 2473

Searching and replacing in binary file

First of all, I tried these questions and didn't work for me:

I'm working in manipulating a pdf file in binary. I need to replace a string by other.

This is my approach:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

with open("proof.pdf", "rb") as input_file:
    content = input_file.read()
    if b"21.8182 686.182 261.818 770.182" in content:
        print("FOUND!!")
    content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")
    if b"1.1 1.1 1.1 1.1" in content:
        print("REPLACED!!")

with open("proof_output.pdf", "wb") as output_file:
    output_file.write(content)

When I run the script it shows "FOUND!!", but not "REPLACED!!"

Upvotes: 1

Views: 5150

Answers (1)

Barun Sharma
Barun Sharma

Reputation: 1468

It is because string replace and sub in python re do not carry out inplace replacements. In both the cases you get another string with your replacement.

Replace:-

content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")

with

content = content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")

This should work.

Upvotes: 3

Related Questions