Wednesday, 1 May 2019

convert io.StringIO to io.BytesIO

i got a StringIO object, how can i convert it into BytesIO?

the naive approach i got is:

import io
sio = io.StringIO('wello horld')
bio = io.BytesIO(sio.read().encode('utf8'))
print(bio.read())  # prints b'wello horld'

is there more elegant way of doing this?

for example, for the reverse question (BytesIO -> StringIO) there exist a class - io.TextIOWrapper which does exactly that (see this answer)



from convert io.StringIO to io.BytesIO

No comments:

Post a Comment