all Python 3ioterm
io
module
The core of input and output: file objects for text and bytes, and in-memory stand-ins StringIO and BytesIO.
Syntax
import io
The built-in open() is io.open, so you import the module not for files on disk but for StringIO and BytesIO: they act like files yet live in memory, which makes them handy fakes in tests. Text and bytes are kept strictly apart: StringIO takes str, BytesIO takes bytes, and the wrong type raises TypeError. After writing, the position sits at the end, so read() returns an empty string until you call seek(0) or use getvalue().
Examples
import io
buf = io.StringIO()
buf.write('first\nsecond\n')
print(repr(buf.read())) # → '' — позиция в конце
buf.seek(0)
print(buf.readline().strip()) # → first
print(io.BytesIO(b'abc').read(2)) # → b'ab'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy