Python Glossary Русский

all Python 3ioterm

io.BufferedReader

binary streams

A buffered binary reading stream over a raw stream; it serves many small read() calls from large blocks.

Syntax

io.BufferedReader(raw)

You seldom build one by hand: open(path, 'rb') returns a BufferedReader, and the .buffer attribute of a text file or of sys.stdin exposes the same layer underneath. Two things the signature does not tell you: read(n) returns exactly n bytes unless the file ends, unlike a raw stream which may hand back fewer, and peek() lets you look ahead without moving the position. Calling read() with no argument pulls the whole file into memory, so read large files in fixed-size chunks or line by line instead.

Examples

import io
b = io.BufferedReader(io.BytesIO(b'hello'))
print(b.read())   # → b'hello'
r = io.BufferedReader(io.BytesIO(b'line1\nline2\n'))
print(r.readline())   # → b'line1\n'
print(r.readlines())   # → [b'line2\n']
p = io.BufferedReader(io.BytesIO(b'abcdef'))
print(p.peek())   # → b'abcdef'
print(p.read(2))   # → b'ab'
print(p.write(b'x'))   # → io.UnsupportedOperation

See also

Open in the full glossarydocs.python.orgReport an inaccuracy