python3 bytes尽可能快地在文件末尾替换%3D by =

时间:2018-05-12 18:06:20

标签: python parsing urllib urldecode

我有一个bytes对象,实际上是dataurl格式的文件。它大约是500 KB。

我需要删除37个字节的标题(我使用切片)并在文件末尾替换%3D(此序列可以找到0-2次)。

Urllib.parse会更改对象中的所有条目。

有没有一种漂亮的方法来处理这个对象?

    content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
    post_body = self.rfile.read(content_length) # <--- Gets the data itself
    print(len(post_body))
    with open("1111", "wb") as fd:
        fd.write(post_body)

    post_body = post_body[37:len(post_body)]

    with open("decoded.png", "wb") as fh:
        fh.write(base64.decodebytes(post_body))

在最后一行我遇到了问题。

&#39; =&#39;可能会添加字符以使最后一个块包含四个base64字符。但是在帖子请求中我有%3D而不是=

1 个答案:

答案 0 :(得分:1)

在我看来,你需要&#34;取消引用&#34;网址已转义(%xx)符号。

Python有一个函数,在python2.7中它是urllib.unquote,在python3中它是urllib.parse.unquote。样本用法是:

from urllib.parse import unquote

post_body = unquote(post_body[37:])
  # my_list[i:] is short for my_list[i:len(my_list)]

但是,我不知道您是否只想将其应用于最后的字节,或仅在字节以%3D结尾时才适用...您可以使用{{1} }适用于字符串和字节相同:

.endswith()
相关问题