You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字节以b'字符串形式写入文件?

问题描述

我希望将imgbytes中的字节序列以前缀为b'的字符串形式写入文件,无需进行编码。但使用write()方法时发现它不接受bytes或bytearray类型的参数,当前代码如下:

from PIL import Image
img = Image.open('some/file.png')
img = img.convert(mode='1')
imgbytes = img.tobytes()
with open('filepath', 'w') as file_out:
    file_out.write(imgbytes)
解决方案

要实现需求,只需将bytes对象转换为带b'前缀的字符串形式即可,以下是两种可行方案:

  • 方案一:使用repr()函数
    repr()会直接返回bytes对象的标准字符串表示(自带b'前缀),直接传入write()即可:
from PIL import Image
img = Image.open('some/file.png')
img = img.convert(mode='1')
imgbytes = img.tobytes()
with open('filepath', 'w') as file_out:
    file_out.write(repr(imgbytes))
  • 方案二:手动拼接字符串
    如果需要自定义格式,可以手动拼接前缀和字节的字符串表示,效果和方案一一致:
from PIL import Image
img = Image.open('some/file.png')
img = img.convert(mode='1')
imgbytes = img.tobytes()
with open('filepath', 'w') as file_out:
    file_out.write(f"b'{imgbytes!r}'")

两种方案写入的都是字符串类型,完全符合write()的参数要求,且无需额外编码处理。

内容的提问来源于stack exchange,提问作者Cutter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 00:04:55