TypeError: string argument expected, got 'bytes'

余生颓废 提交于 2021-02-11 13:42:10

问题


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()) 

回答1:


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)

See also io — Core tools for working with streams



来源:https://stackoverflow.com/questions/62903409/typeerror-string-argument-expected-got-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!