io.BytesIO, io.StringIO
class io.BytesIO(initial_bytes=b'')
class io.StringIO(initial_value='', newline='\n')
stream.read(size=-1)
stream.tell()
stream.seek(offset, whence=0)Use BytesIO for in-memory bytes and StringIO for in-memory text. Their seek units differ: bytes versus characters.
| Parameter | Description |
|---|---|
initial_bytes / initial_value | Optional starting contents. BytesIO takes bytes; StringIO takes str. |
size, offset, whence | read returns up to size items, or the rest if size is negative or omitted. seek uses a byte offset on BytesIO and a character offset on StringIO when whence is 0. |
Returns: read returns bytes on BytesIO and str on StringIO. tell and seek return the new position in the same units.
- In the StringIO example, "hé" is two characters. tell() is 2, and seek(1) resumes at "é". That character indexing is a StringIO behavior, not the rule for a text file on disk.
import io
buf = io.BytesIO(b"abcdef")
print(buf.read(2), buf.tell())
buf.seek(3)
print(buf.read())
text = io.StringIO("héllo")
print(text.read(2), text.tell())
text.seek(1)
print(text.read())Expected output
b'ab' 2
b'def'
hé 2
éllo