TypeError:预期为字符串参数,获取了“字节" [英] TypeError: string argument expected, got 'bytes'
本文介绍了TypeError:预期为字符串参数,获取了“字节"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将以下十六进制序列转换为图像,在筛选与我相似的许多问题的过程中,没有一个问题与
I would like to convert the below hex sequences to images, in the process of sifting through quite a number of problems that are similar to mine none have come close as to that solved in https://stackoverflow.com/a/33989302/13648455, my code is below, where could I be going wrong?
data = "2a2b2c2a2b2c2a2b2c2a2b2cb1"
buf = io.StringIO()
for line in data.splitlines():
line = line.strip().replace(" ", "")
if not line:
continue
bytez = binascii.unhexlify(line)
buf.write(bytez)
with open("image.jpg", "wb") as f:
f.write(buf.getvalue())
推荐答案
io.StringIO()
创建一个字符串对象,该对象产生文本流.您需要 io.BytesIO()
代替,它会创建一个字节对象,您可以在其中写入二进制数据:
io.StringIO()
creates a string object which yields a text stream.
You need io.BytesIO()
instead, which creates a bytes object to which you can write your binary data:
buf = io.BytesIO()
...
buf.write(bytez)
另请参见 io-用于处理流的核心工具
这篇关于TypeError:预期为字符串参数,获取了“字节"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文