1

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!!"

Community
  • 1
  • 1
Trimax
  • 2,413
  • 7
  • 35
  • 59

1 Answers1

3

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.

Barun Sharma
  • 1,452
  • 2
  • 15
  • 20