Decode the bytes object to produce a string:

>>> b"abcde".decode("utf-8")
'abcde'

The above example assumes that the bytes object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!

Answer from Aaron Maenpaa on Stack Overflow
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-convert-strings-to-bytes-in-python
How to convert strings to bytes in Python
We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.
Discussions

python - convert io.StringIO to io.BytesIO - Stack Overflow
And the example continues with BytesIO -> StringIO. ... You should update the title. It contradicts the updated statement. It confused me and can likely confuse other people. ... It's interesting that though the question might seem reasonable, it's not that easy to figure out a practical reason why I would need to convert ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Converting bytes to string to bytes
How can I convert bytes to string to bytes back? Hereโ€™s what Iโ€™m trying: from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding message = b"A message I want to sign" signature = private_key.sign( message, padding.PSS( mgf=padding... More on discuss.python.org
๐ŸŒ discuss.python.org
8
0
October 28, 2021
How to convert bytes to string in python?
Try this: line = ser.readline().strip() values = line.decode('ascii').split(',') a, b, c = [int(s) for s in values] The call to .strip() removes the trailing newline. The call .decode('ascii') converts the raw bytes to a string. .split(',') splits the string on commas. Finally the call [int(s) for s in value] is called a list comprehension, and produces a list of integers. More on reddit.com
๐ŸŒ r/Python
3
1
February 8, 2016
Part of string is UTF8 encoded, can't decode
can your terminal/IDE handle unicode output? More on reddit.com
๐ŸŒ r/learnpython
12
4
October 22, 2020
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ string-to-bytes-conversion
How to Convert String to Bytes in Python | DataCamp
June 5, 2024 - In Python, use the .encode() method on a string to convert it into bytes, optionally specifying the desired encoding (UTF-8 by default).
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ python-string-to-bytes
How to convert Python string to bytes? | Flexiple Tutorials | Python - Flexiple
Note: This method converts objects into immutable bytes, if you are looking for a mutable method you can use the bytearray() method. The encode() method is the most commonly used and recommended method to convert Python strings to bytes.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-io-bytesio-stringio
Python io.BytesIO and io.StringIO: Memory File Guide | DigitalOcean
August 3, 2022 - Just like what we do with variables, ... \x00\x01") print(stream_str.getvalue()) Letโ€™s see the output for this program: The getvalue() function just takes the value from the Buffer as a String....
Top answer
1 of 6
45

It's interesting that though the question might seem reasonable, it's not that easy to figure out a practical reason why I would need to convert a StringIO into a BytesIO. Both are basically buffers and you usually need only one of them to make some additional manipulations either with the bytes or with the text.

I may be wrong, but I think your question is actually how to use a BytesIO instance when some code to which you want to pass it expects a text file.

In which case, it is a common question and the solution is codecs module.

The two usual cases of using it are the following:

Compose a File Object to Read

In [16]: import codecs, io

In [17]: bio = io.BytesIO(b'qwe\nasd\n')

In [18]: StreamReader = codecs.getreader('utf-8')  # here you pass the encoding

In [19]: wrapper_file = StreamReader(bio)

In [20]: print(repr(wrapper_file.readline()))
'qwe\n'

In [21]: print(repr(wrapper_file.read()))
'asd\n'

In [26]: bio.seek(0)
Out[26]: 0

In [27]: for line in wrapper_file:
    ...:     print(repr(line))
    ...:
'qwe\n'
'asd\n'

Compose a File Object to Write To

In [28]: bio = io.BytesIO()

In [29]: StreamWriter = codecs.getwriter('utf-8')  # here you pass the encoding

In [30]: wrapper_file = StreamWriter(bio)

In [31]: print('ะถะฐะฑะฐ', 'ั†ะฐะฟ', file=wrapper_file)

In [32]: bio.getvalue()
Out[32]: b'\xd0\xb6\xd0\xb0\xd0\xb1\xd0\xb0 \xd1\x86\xd0\xb0\xd0\xbf\n'

In [33]: repr(bio.getvalue().decode('utf-8'))
Out[33]: "'ะถะฐะฑะฐ ั†ะฐะฟ\\n'"
2 of 6
4

@foobarna answer can be improved by inheriting some io base-class

import io
sio = io.StringIO('wello horld')


class BytesIOWrapper(io.BufferedReader):
    """Wrap a buffered bytes stream over TextIOBase string stream."""

    def __init__(self, text_io_buffer, encoding=None, errors=None, **kwargs):
        super(BytesIOWrapper, self).__init__(text_io_buffer, **kwargs)
        self.encoding = encoding or text_io_buffer.encoding or 'utf-8'
        self.errors = errors or text_io_buffer.errors or 'strict'

    def _encoding_call(self, method_name, *args, **kwargs):
        raw_method = getattr(self.raw, method_name)
        val = raw_method(*args, **kwargs)
        return val.encode(self.encoding, errors=self.errors)

    def read(self, size=-1):
        return self._encoding_call('read', size)

    def read1(self, size=-1):
        return self._encoding_call('read1', size)

    def peek(self, size=-1):
        return self._encoding_call('peek', size)


bio = BytesIOWrapper(sio)
print(bio.read())  # b'wello horld'
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-convert-string-to-bytes
Convert String to bytes-Python - GeeksforGeeks
Explanation: bytes() constructor converts a string to bytes using the specified encoding, here "utf-8", allowing the string to be processed as binary data.
Published ย  July 11, 2025
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ stringio-and-bytesio-for-managing-data-as-file-object
Stringio And Bytesio For Managing Data As File Object - GeeksforGeeks
July 24, 2025 - In this example, a new BytesIO object named binary_buffer is created to emulate an in-memory file for binary data. The hexadecimal representation of the string "Hello" is written to the buffer using write.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ bytes-to-string-python
How to Convert Bytes to String in Python | DataCamp
June 12, 2024 - Python displays the hexadecimal representation of these bytes. However, .decode() returns a string by decoding the bytes object using the UTF-8 encoding. The pair of bytes b'\xc3\xa9' represent the letter e with an acute accent, รฉ. The .decode() method takes an optional argument to specify the encoding: ... UTF-8 is the default encoding, but other encodings can be used. We can also convert a string to a bytes object using the string method .encode() with various encodings:
๐ŸŒ
Real Python
realpython.com โ€บ python-bytes
Bytes Objects: Handling Binary Data in Python โ€“ Real Python
January 20, 2025 - It can be especially useful when you want to print and align multiple bytes in columns or rows. Because hex is such a widespread notation, Python provides a convenient class method in its bytes data type, which converts a string of hexadecimal digits into a new bytes instance:
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ io.html
io โ€” Core tools for working with streams
January 30, 2026 - BufferedRandom provides a buffered interface to seekable streams. Another BufferedIOBase subclass, BytesIO, is a stream of in-memory bytes. The TextIOBase ABC extends IOBase. It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-bytes-to-string-how-to-convert-a-bytestring
Python Bytes to String โ€“ How to Convert a Bytestring
April 10, 2023 - In this example, we define a byte string b"Hello, world!" and use the str() constructor to convert it to a string object. We specify the encoding format as utf-8 using the encoding parameter.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ convert a string to bytes in python
Convert a string to bytes in Python | Sentry
July 15, 2023 - my_string = "A string to turn into bytes." print(type(my_string)) # will print "<class 'str'>" my_bytes = my_string.encode() print(type(my_bytes)) # will print "<class 'bytes'>"
๐ŸŒ
Net Informations
net-informations.com โ€บ python โ€บ iq โ€บ byte.htm
How to convert bytes to string in Python?
convert bytes to string in Python convert string to bytes in Python , We can convert bytes to String using bytes class decode() instance method, So you need to decode the bytes object to produce a string.
๐ŸŒ
Plain English
python.plainenglish.io โ€บ how-to-use-io-stringio-and-io-bytesio-in-python-c7e10c3180b8
How to use io.StringIO and io.BytesIO in Python | by Lynn G. Kwong | Python in Plain English
November 1, 2024 - New Python content every day. Follow to join our 3.5M+ monthly readers. ... Lynn G. Kwong ... The StringIO and BytesIO classes of the io module are in-memory file-like objects in Python. They allow us to use a string buffer or a bytes buffer as if it were a file.
๐ŸŒ
w3resource
w3resource.com โ€บ python โ€บ python-bytes.php
Python Bytes, Bytearray
June 6, 2024 - If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ converting python bytes to stringio
Converting Python Bytes to StringIO - Be on the Right Side of Change
February 23, 2024 - In this snippet, TextIOWrapper wraps around a BytesIO object to deal seamlessly with encoding. This is particularly useful for complex text processing that involves different encodings and newline handling. This approach is slightly more complex and involves creating a memoryview object from the bytes data before decoding it. This method can be efficient for large data sets as it provides a way to work with a slice of the bytes without copying the original data. ... from io import StringIO bytes_data = b'This is a memoryview example' memory_view = memoryview(bytes_data) string_data = memory_view.tobytes().decode('utf-8') string_io = StringIO(string_data) print(string_io.getvalue())