On this page
io.StringIO
Prev: io.Reader | Up: io | Next: io.text_encoding
Rel: io.BlockingIOError, io.BufferedIOBase, io.BufferedRandom, io.BufferedReader
Ref: docs.python.org — io.StringIO
Tags: #public #python3 #stdlib #io
Import
import io
from io import StringIO
Signature & Overview
io.StringIO(initial_value='', newline='\n')
Text I/O implementation using an in-memory buffer.
Methods & Attributes
StringIO.close(self, /)— Close the IO object.StringIO.detach(self, /)— Separate the underlying buffer from the TextIOBase and return it.StringIO.fileno(self, /)— Return underlying file descriptor if one exists.StringIO.flush(self, /)— Flush write buffers, if applicable.StringIO.getvalue(self, /)— Retrieve the entire contents of the object.StringIO.isatty(self, /)— Return whether this is an 'interactive' stream.StringIO.read(self, size=-1, /)— Read at most size characters, returned as a string.StringIO.readable(self, /)— Returns True if the IO object can be read.StringIO.readline(self, size=-1, /)— Read until newline or EOF.StringIO.readlines(self, hint=-1, /)— Return a list of lines from the stream.StringIO.seek(self, pos, whence=0, /)— Change stream position.StringIO.seekable(self, /)— Returns True if the IO object can be seeked.StringIO.tell(self, /)— Tell the current file position.StringIO.truncate(self, pos=None, /)— Truncate size to pos.StringIO.writable(self, /)— Returns True if the IO object can be written.StringIO.write(self, s, /)— Write string to file.StringIO.writelines(self, lines, /)— Write a list of lines to stream.
Usage
import io
buf = io.StringIO()
buf.write("line 1\n")
buf.write("line 2\n")
assert buf.getvalue() == "line 1\nline 2\n"
buf.seek(0)
assert buf.readline() == "line 1\n"
Gotchas
- Text (
str) only: WritingbytesraisesTypeError(useBytesIOfor binary data). getvalue()vs.read():getvalue()always returns the full buffer regardless of cursor position, whileread()starts from the current cursor.
REPL Inspect
from io import StringIO
help(StringIO)
Linked from
Related notes
- tuts/python3/stdlib_module/io/Reader Linked here; links to this page; shared tags: #io, #stdlib
- tuts/python3/stdlib_module/io/text_encoding Linked here; links to this page; shared tags: #io, #stdlib
- tuts/python3/stdlib_module/io Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BlockingIOError Linked here; shared tags: #io, #stdlib
- tuts/python3/stdlib_module/io/BufferedIOBase Linked here; shared tags: #io, #stdlib
- tuts/python3/stdlib_module/io/BufferedRandom Linked here; shared tags: #io, #stdlib
- tuts/python3/stdlib_module/io/BufferedReader Linked here; shared tags: #io, #stdlib
- tuts/c/stdlib/stdio_and_file_io shared tags: #io, #stdlib
- tuts/cpp/stdlib/io_and_filesystem shared tags: #io, #stdlib
- tuts/cpp/stdlib/io_and_filesystem/format_and_print shared tags: #io, #stdlib