预期为字符串参数,在buffer.write中获得了“字节”

Mig*_*tos 2 python file

我有这个:

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'
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*sta 7

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

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())
Run Code Online (Sandbox Code Playgroud)