在二进制文件中搜索和替换
Searching and replacing in binary file
首先,我尝试了这些问题,但对我没有用:
- Python search and replace in binary file
- python re module to replace the binary data inside a text file?
我正在处理二进制格式的 pdf 文件。我需要用其他字符串替换字符串。
这是我的方法:
#!/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)
当我 运行 脚本显示 "FOUND!!",而不是 "REPLACED!!"
因为pythonre
中的string replace
和sub
没有进行原地替换。在这两种情况下,您都会得到另一个替换字符串。
替换:-
content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")
和
content = content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")
这应该有效。
首先,我尝试了这些问题,但对我没有用:
- Python search and replace in binary file
- python re module to replace the binary data inside a text file?
我正在处理二进制格式的 pdf 文件。我需要用其他字符串替换字符串。
这是我的方法:
#!/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)
当我 运行 脚本显示 "FOUND!!",而不是 "REPLACED!!"
因为pythonre
中的string replace
和sub
没有进行原地替换。在这两种情况下,您都会得到另一个替换字符串。
替换:-
content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")
和
content = content.replace(b"21.8182 686.182 261.818 770.182", b"1.1 1.1 1.1 1.1")
这应该有效。