如何将字节以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
相关产品推荐
相关产品推荐

