【问题标题】:Searching and replacing in binary file在二进制文件中搜索和替换
【发布时间】:2015-06-19 21:20:38
【问题描述】:

首先,我尝试了这些问题并没有为我工作:

我正在处理二进制格式的 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!!”

【问题讨论】:

    标签: python python-3.x file-io replace binary


    【解决方案1】:

    这是因为python中的string replacesubre不进行就地替换。在这两种情况下,您都会得到另一个替换字符串。

    替换:-

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

    这应该可行。

    【讨论】:

      猜你喜欢
      • 2011-03-10
      • 1970-01-01
      • 2019-04-21
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2016-02-28
      相关资源
      最近更新 更多