将用于解压缩 base64 编码位图图像的 Python 2.7 代码转换为 Python 3.7

Converting Python 2.7 code used to decompress a base64 encoded bitmap image to Python 3.7

我有一些在 Python 2.7 中工作的代码,但我现在正在尝试学习 Python 3 并转换几个遗留脚本。我使用 base64.b64decode 解码包含位图图像的文件的每一行(每行一个),然后 StringIO.StringIOgzip.GzipFile 解压缩为字符串。

我可能需要重新评估整个过程。如果在 Python 3 中有更有效的方法来实现这一点,我愿意学习它,只是为我指明了正确的方向。

我找到了 io 替换 StringIO 的地方,但是当我使用 io.BytesIO 时,我收到有关文件结尾标记的错误。或者,io.StringIO 会给我关于尚未 strNone 的输入类型的错误。

我已经尝试了几种不同的方法来将 io.BytesIO 的输出转换回字符串,但我没有尝试将 运行 遇到的每个错误都覆盖到让我们只是说我被卡住了。

旧版 Python 2.7 代码:

import base64
nowtext= "c:/input_path/"
nowhtml= "c:/output_path/"
with open (nowtext, 'r') as f:
    for line in f:
        zipped= base64.b64decode(line)
        import StringIO
        sio= StringIO.StringIO(zipped)
        import gzip
        u= gzip.GzipFile(fileobj=sio)
        unzipped= u.read()
        wrapper= """<img src="data:image/bmp;base64,%s" />"""
        h= open (nowhtml,'a')
        h.write(wrapper % unzipped + '\n')

尝试转换 Python 3

import base64
nowtext= "c:/input_path/"
nowhtml= "c:/output_path/"
with open (nowtext, 'r') as f:
    for line in f:
        zipped= base64.b64decode(line)
        import io
        sio= io.BytesIO(zipped)
        import gzip
        u= gzip.decompress(sio)
        unzipped= u.read()
        wrapper= """<img src="data:image/bmp;base64,%s" />"""
        h= open (nowhtml,'a')
        h.write(wrapper % unzipped + '\n')

您不需要将数据包装在一个文件对象中加上一个 GzipFile() 对象来解压。只需使用 gzip.decompress() function 直接 解压缩您的数据。您的代码混淆了 gzip.GZipFile()gzip.decompress();不要将一个文件对象传递给直接作用于 bytes 值的函数。

我假设解码后的数据本身就是一个有效的 Base64 字符串(否则你的 Python 2 代码无法工作),所以我们需要解码你的 bytes 值解压得到,用ASCII码解码:

import base64
import gzip

nowtext= "c:/input_path/"
nowhtml= "c:/output_path/"

with open(nowtext, 'r') as f, open(nowhtml, 'a') as output:
    for line in f:
        unzipped = gzip.decompress(base64.b64decode(line)).decode('ascii')
        line = f'<img src="data:image/bmp;base64,{unzipped}" />\n'
        output.write(line)

请注意,我只打开输出文件一次。通过为每一行一次又一次地打开文件来减慢脚本速度没有什么意义。