Python Reference ยท Files, Paths and Text I/O
io.StringIO and BytesIO
Reference for io.StringIO and io.BytesIO: in-memory text and binary files, getvalue(), seek(0), testing file code and capturing output.
io.StringIO and io.BytesIO are file-like objects that keep their data in memory instead of on disk. StringIO holds text (str), BytesIO holds bytes. They support the same methods as real files: read(), write(), readline(), iteration, seek() and tell().
Use them when a function expects a file but your data is already in a variable, when you want to build a large string piece by piece, or when you want to test file-handling code without touching the disk.
import io buffer = io.StringIO() buffer.write("hello") print(buffer.getvalue()) # hello
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
io.StringIO(initial_value="", newline="\n") io.BytesIO(initial_bytes=b"")
| Name | Description |
|---|---|
initial_value |
Starting text for a StringIO. The position starts at 0 (the beginning). |
initial_bytes |
Starting content for a BytesIO. |
newline |
StringIO only. Same meaning as in open(); the default "\n" performs no translation. |
Key methods beyond the usual file API:
| Method | Description |
|---|---|
getvalue() |
Returns the entire contents (str or bytes), regardless of the current position. |
getbuffer() |
BytesIO only. Returns a memoryview of the contents without copying. |
truncate(size) |
Cuts the contents to size; use seek(0) and truncate() to reuse a buffer. |
close() |
Frees the buffer. Any later use raises ValueError. |
Return value: a file-like object.
Raises: TypeError when you write the wrong type (bytes to StringIO, text to BytesIO), and ValueError after close().
Usage notes
- The position starts at 0, and each write moves it forward. After writing, the position is at the end, so call
seek(0)beforeread(), or usegetvalue(), which ignores the position. Writing into a buffer created with an initial value overwrites that value from the start. - Replace file-based tests. Pass
StringIO("...")to a parser, and read the result withgetvalue(), so tests need no temporary files. - Building strings. Many
write()calls into aStringIOfollowed by onegetvalue()is a fast alternative to repeated+=on very large strings, though"".join(list)is usually even simpler. - Capturing output.
contextlib.redirect_stdout(StringIO())collects whatprint()writes.print(..., file=buffer)writes to a specific buffer. - No file on disk and no encoding.
StringIOstores characters, andBytesIOstores raw bytes; there is noencodingargument. Encode text yourself withstr.encode()for aBytesIO. - Reusing a buffer. Writing after
seek(0)overwrites from the start without shrinking the buffer. Calltruncate()after seeking if you want a fresh start. getbuffer()pins the buffer. While the returned view exists, theBytesIOcannot be resized or closed; release the view first.- Context manager.
with io.StringIO() as f:closes the buffer at the end of the block, after whichgetvalue()no longer works; read the value inside the block.