Python Glossary Русский

all Python 3ioterm

io.StringIO

strings

A file-like object that keeps string data in memory. Convenient for testing and for buffering.

Syntax

io.StringIO(initial_value='', newline='\n')

One cursor serves both reading and writing: after a write() it sits at the end, so read() gives an empty string until you seek(0) — getvalue() returns the whole buffer regardless of position. close() throws the buffer away and getvalue() then raises ValueError, so grab the value before leaving the with block. It holds str only; for bytes use io.BytesIO.

Examples

import io
buf = io.StringIO()
buf.write('hello\n')
buf.write('world')
buf.getvalue() # → 'hello\nworld'
buf.seek(0)
buf.read() # → 'hello\nworld'
s = io.StringIO('line1\nline2')
list(s) # → ['line1\n', 'line2']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy