预期为字符串参数,在buffer.write中获得了“字节" [英] string argument expected, got 'bytes' in buffer.write

查看:59
本文介绍了预期为字符串参数,在buffer.write中获得了“字节"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

from io import StringIO
buffer = StringIO()

latest_file = 'C:\\Users\\miguel.santos\\Desktop\\meo_snapshots\\Snapshot_14.jpg'

buffer.write(open(latest_file,'rb').read())

TypeError: string argument expected, got 'bytes'

关于如何解决的任何想法?

Any ideas on how to solve?

推荐答案

io.StringIO 用于unicode文本,对应的字节为 io.BytesIO .由于您的永久文件是二进制jpg,因此您实际上应该使用后者:

io.StringIO is for unicode text, its counterpart for bytes is io.BytesIO. As your undelying file is a binary jpg, you really should use the latter:

from io import BytesIO
buffer = BytesIO()

latest_file = 'C:\\Users\\miguel.santos\\Desktop\\meo_snapshots\\Snapshot_14.jpg'

buffer.write(open(latest_file,'rb').read())

这篇关于预期为字符串参数,在buffer.write中获得了“字节"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆