22

I have this:

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?

2
  • Don't use rb as it gives you bytes object, use r. Commented Jun 11, 2018 at 11:55
  • 3
    @zipa Probably, more consistent would be to not use StringIO for binary data (it's hard to use 'r' to read a JPEG file I assume.) Commented Jun 11, 2018 at 11:59

1 Answer 1

50

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())
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed the io.BytesIO in py3 corresponds to cStringIO.StringIO in py2 better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.